Hello i have a query im trying to run with laravel 8 where i have 2 tables (drivers and cards) 1 driver can have multiple cards. Each card has a expiration. Im trying to get a list of the drivers and the cards that are expiring within 30 days or already expired HOWEVER i need to get only the latest expiration 1 and see if that is expiring within 30 days since they can have uploaded a newer one expiring later
So currently i have this query
DB::table('drivers')
->join('driver_card', 'drivers.driver_id', 'driver_card.driver_id')
->select('driver_card.*', 'drivers.email', 'drivers.first_name', 'drivers.last_name')
->where('drivers.is_active',1)
->where('driver_card.is_active', 1)
->where('drivers.id_company', $id_company)
->where('driver_card.expiration_date', "<=", date('Y-m-d', strtotime('+30 days')))
->paginate(25);
The problem with this is if "Joe" has a card that expires in 25 days but they also have a card that expires in 180 days the 25 day expiration card shows up but it shouldnt since the latest expiration card they have is greater than 30 days. Hope that makes sense anyone know how to do this.
So i have a raw sql Query that works how i wanted:
select a.first_name, a.last_name , b.* from drivers a
join driver_card b on a.driver_id = (
select driver_id from driver_card where id_company = 5 order by expiration_date DESC limit 1
)
where a.is_active = 1
and b.expiration_date <= '2022-05-31'
and b.driver_id NOT IN (select driver_id from driver_card where expiration_date > '2022-05-31')