Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hjortur17's avatar

Help with whereDoesntHave query

Hi, I'm trying to create a table which holds records of assigned cars. So when a car is assigned to a booking it gets added to this table assigned_cars which is a Car belongsToMany Bookings relationship.

But what I'm struggling with is the query to get available cars. Doesn't matter what the pick-up date is. It seems like if the car has already been booked once before that it will not show again in the list. This is how my query looks like:

$cars = Car::query()
            ->whereDoesntHave('booking', function (Builder $builder) use ($bookingCriteria) {
                $builder->where('pick_up_date', '<=', $bookingCriteria['toDate']);
                $builder->where('drop_off_date', '>=', $bookingCriteria['fromDate']);
            })
            ->get();

Any idea how to fix this query?

0 likes
3 replies
AungHtetPaing__'s avatar
Level 22

@hjortur17

$cars = Car::query()
            ->whereDoesntHave('booking', function (Builder $builder) use ($bookingCriteria) {
                $builder->where('pick_up_date', '<=', $bookingCriteria['toDate'])
                				->where('drop_off_date', '>=', $bookingCriteria['fromDate']);
            })
            ->get();
hjortur17's avatar

I changed my query to match @aunghtetpaing__ and also changed the format of my dates stored in database and it seems like it solved it.

Please or to participate in this conversation.