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

KalimeroMK's avatar

query Not filtering by date

Hi all Need to show all vehicles witch are free according to the date but filtering by date is not working my code is

$query->where(function ($query) use ($end_datetime, $start_datetime) {
                        return $query
                            ->whereDoesntHave('vehicle_rental_times')
                            ->orWhereHas('vehicle_rental_times', function ($q) use ($start_datetime, $end_datetime) {
                                return
                                    $q->Where('booking_start_datetime', '>', $end_datetime)
                                      ->Where('booking_end_datetime', '>', $start_datetime);
                            });
                    }
                    );

in vehicle model have method

/**
         * @return HasMany
         */
        public function vehicle_rental_times(): HasMany
        {
            return $this->hasMany(VehicleRentalTime::class);
        }

the query doesn't filtered the data returns all row not filtering according to the date

0 likes
2 replies
Sofia's avatar

$q->Where('booking_start_datetime', '>', $end_datetime)

Greater than end time?

If that doesn't resolve it, inspect the actual query being generated. Also make sure your $end_datetime and $start_datetime formats are consistent with what the DB expects.

MohamedTammam's avatar
Level 51

I think you are mistaking the order.

$query->whereDoesntHave('vehicle_rental_times', function ($query) use ($end_datetime, $start_datetime) {
		$query->WhereNotBetween('booking_start_datetime', [$start_datetime, $end_datetime])
				->WhereNotBetween('booking_end_datetime', [$start_datetime, $end_datetime]);
});

Please or to participate in this conversation.