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

Mohamed_Hammad's avatar

Laravel Query

I have a car rental system, i need to return available cars on this endpoint "get available cars".
the body contains "receive_time" and "deliver_time" which i will check my orders in db if it contains orders on this time or not.
i need to write the correct query for this case i can't do it.

code

		$cars = $this->car->query()->where('garage_id',$garage_id)->whereDoesntHave('orders', function($query) use($recive_date,$recive_time,$deliver_date,$deliver_time,$recive,$deliver) {
        $query
        ->whereBetween('receive_time', [$recive_date, $deliver_date])
        ->whereIn('order_status', ['Pending','OnGoing']);})->get();
0 likes
6 replies
JakeCausier's avatar

Is there a reason why you use two different variables for date ($receive_date) and time ($receive_time) in each instance? If you are comparing receive_time (09:30:00) with $receive_date (28-11-22), that wouldn't work. I'm just guessing from the variables, but if this is wrong, please let me know.

You should store the data in your table as a proper datetime such as 28-11-22 09:30:00, which will let you use whereBetween with dates properly.

2 likes
Randy_Johnson's avatar

I don't know whats going off here but you should use eloquent. And then you could set your databases as such.

Database Tables Car, Rental

Car id, type, model, etc

Rental id, car_id, receive_date, deliver_date

I am guessing the customer would then send input of their date they want, which could be then processed as such

$receive_date = $request['receive_date'];
$deliver_date = $request['deliver_date'];
$cars = Car::all();
$available_cars = collection();
foreach ($cars as $car)
{
	if ($car->rental->receive_date < $receive_date && $car->rental->deliver_date > $deliver_date)
	{	
			$available_cars.add($car);
	}
}

dd($available_cars);

Must dash, hope this helps.

I should add this is done using eloquent.

1 like
jaseofspades88's avatar

@Randy_Johnson I would advise against fetching all cars from the database and iterating over each one because this is not a scalable solution. If you have 1000 cars but only 2 valid rentals, you'd have to iterate over 998 cars unnecessarily.

1 like
Randy_Johnson's avatar

@jaseofspades88 Ive never found a car rental company with over 1000 cars. They usually have 20 to 30 cars, and that is in the big cities.

$car = Car::where($car->rental->receive_date, '<' $receive_date, '&&', $car->rental->deliver_date, '>', $deliver_date)

Is this possible. Seriously thinking about programming a car rental site just for the practice.

Can you please link and documentation which will help towards the solution.

1 like

Please or to participate in this conversation.