Optimizing Nested Loops in Laravel Blade for Availability Checks
In a venue management system, displaying available time slots against booked ones is a common requirement. The logic seems straightforward: iterate through your timetable, check if a slot exists in the bookings table, and render the appropriate status. However, the implementation details often lead to performance bottlenecks or, as seen in many early-stage Laravel projects, incorrect data rendering.
Consider this scenario where you have two variables passed to the view: $times from the Times model and $bookings from the Bookings model. The goal is to display every available time slot, marking it as "not available" only if a matching booking exists. A naive approach often looks like this in Blade:
@foreach($times as $time)
@foreach($bookings as $booking)
<tr>
@if($time->availble_times == $booking->booking_time)
<td>{{ $time->availble_times }}: not available</td>
@else
<tr><td>{{ $time->availble_times }}</td>
@endif
</tr>
@endforeach
@endforeach
While this code attempts to solve the problem, it fails because of how nested loops operate. The outer loop iterates through $times, but for every single time slot, the inner loop iterates through all rows in the $bookings collection. If you have 50 available slots and 10 bookings, this results in 500 iterations of the inner check per row. More critically, it does not break once a match is found. Consequently, if a time slot exists but has no booking, the loop continues to check every other booking record, potentially rendering multiple rows for the same time or simply failing to break out of the logic flow correctly within the HTML structure.
The specific issue you observedâwhere times appear multiple times or the table row count explodesâis due to the fact that the inner foreach processes the entire $bookings array for every iteration of the outer $times loop. This is an O(n²) complexity problem relative to the number of bookings, which degrades instantly as your venue fills up with events.
To fix this, you should shift the logic from nested loops to a single-pass operation using collect and intersectBy. Laravel's collection methods are designed to handle these set operations efficiently. You can transform the $bookings data into a collection of booking times and then use intersectBy (available in PHP 8.1+ via Laravel) or simply check for existence within a single loop.
Here is a corrected approach that maintains readability while fixing the duplication:
@php
// Create a set of booked times for O(1) lookups
$bookedTimes = collect($bookings)->pluck('booking_time')->unique()->toArray();
@endphp
@foreach($times as $time)
@if(in_array($time->availble_times, $bookedTimes))
<td class="unavailable">{{ $time->availble_times }}: not available</td>
@else
<td class="available">{{ $time->availble_times }}</td>
@endif
@endforeach
This approach first extracts the unique booking times into an array. In PHP, checking if an element exists in an array using in_array is fast for small datasets, but more importantly, this logic runs once per time slot rather than looping through all bookings repeatedly. If you are using a newer version of Laravel that supports collections with PHP 8.1 features, you could even use $times->intersectBy($bookedTimes) to filter the collection before rendering, though checking availability inside the loop gives you more control over the HTML generation.
Another consideration is data integrity. Ensure that availble_times and booking_time are stored in a consistent format (e.g., both as timestamps or both as formatted strings). Mixing formats (like one being a Carbon instance and the other a string) will cause comparisons to fail even if the logic is correct.
Finally, while the view handles the presentation layer, consider optimizing the controller. If you have thousands of bookings, fetching Bookings::all() might be heavy. You could use a query like DB::table('bookings')->select('booking_time')->pluck('booking_time') to get just the times needed, reducing memory overhead before passing data to the view. For larger systems, caching this list of booked times for a specific day or venue might be necessary to prevent database load spikes during peak traffic hours.
