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

farshadf's avatar

how to query database for each day in an array of days laravel

i have an array of days that i want to query my model for each date that i have in that array , that could be possible with a for loop and index but as thumbs rules i dont want to query inside a loop so is there any other possibility to check the date in my model so my tried with for loop is like below :

     $period = CarbonPeriod::create($from_date, $to_date);
        $dates = $period->toArray();
// and here l am looping the days :
for ($t = 0; $t < count($dates); $t++) {
                   $room_capacity = Capacity::with('Hotel')
                    ->where('room_id', $room_ids[$i])
                    ->whereDate('from_date', '<=', $dates[$t])
                    ->whereDate('to_date', '>=', $dates[$t])
                    ->get()->sortBy('created_at');
}

i want to know if there is any way to potimize the above code not to write it inside a loop . thanks

0 likes
2 replies
aurawindsurfing's avatar

Hey @farshadf

Modify it to your needs but something like that will do the trick:

$room_capacity = Capacity::query()
            ->whereBetween('date', [
                Carbon::now()->startOfMonth()->subMonth()->toDateString(),
                Carbon::now()->startOfMonth()->subMonth()->endOfMonth()->toDateString(),
            ])
            ->get();

This here makes no sense:

->whereDate('from_date', '<=', $dates[$t])

It actually should be:

->where('date', '<=', $dates[$t])

Also if you try to do a booking system then try to think in a smallest possible interval when you think about your reservations. For instance if room can only be booked for 1 day, then instead of creating from_date to_date you could create 31 days in a given month and then create lets say 4 consecutive bookings for one day for that room - meaning it would be booked for 4 days.

This type of approach will make your system more flexible and easier to work with.

You can even go down to hours and book rooms per hours. Even go down to minutes etc etc. Your future queries would be much simpler then as well.

Hope it helps!

1 like
Tray2's avatar

If it's every date between to dates (1st, 2nd, 3rd, 4th and 5th) I would use something similar to aurawindsurfings suggestion but if it's sporadic date like 1st, 3rd, 5th, 8th,14th, and 31st I would use whereIn

$result = MyNiftyModel::whereIn('created_at', $dateArray)->get();
1 like

Please or to participate in this conversation.