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

hjortur17's avatar

Laravel blade doesn't render all from foreach

Hi, I have a Booking and Service table and a pivot table to connect them. I'm trying to get the services for these bookings but it always renders the else statement:

@if (!$booking->services->isEmpty())
        <div class="flex my-4">
            <div class="w-64 self-center">
                <h3 class="font-light text-xl">Þjónusta:</h3>
            </div>
            <div class="flex-1 text-right">
                <ul>
                    @foreach ($booking->services as $service)
                        <li>
                            <p class="font-bold">{{ $service->description }}</p>
                        </li>
                    @endforeach
                </ul>
            </div>
        </div>
    @else
        <div class="flex my-4">
            <h3 class="font-light text-xl italic">Ekki var valið þjónusta</h3>
        </div>
    @endif

I have a booking inside my database (id: 14) and then I have a row in booking_service (14, 3) and then I have a service in my database (id: 3). And I'm trying to get the description of the service.

It was working before, then I changed from this:

$bookings = Booking::where('dropOffDate', $today)->orderBy('flightTime', 'asc')->get();

to this:

$bookings = Booking::where('dropOffDate', $today) ->orWhere('pickUpDate', $today) ->orderBy('flightTime', 'asc') ->get();

0 likes
6 replies
adityakunhare's avatar

In blade you are using $booking where in the controller you have declared the variable $booking"s". May be that could be the solution.

hjortur17's avatar

I have a foreach loop running though bookings as booking

Cronix's avatar

Give an example of what a value for $today is.

Also, what are the database datatypes for your dropOffDate and pickUpDate fields?

Snapey's avatar

you need to eager load the services, or else they will be null

hjortur17's avatar

Here is the function:

public function today()
    {
        // $bookings = Booking::orderBy('dropOffDate', 'asc')->get();
        // $today = date("d/m/Y");

        $date = date_create("2019-09-30");
        $today = date_format($date, "d/m/Y");

        $bookings = Booking::where('dropOffDate', $today)
            ->orWhere('pickUpDate', $today)
            ->orderBy('flightTime', 'asc')
            ->get();

        return view('dashboard.today', compact('bookings'));
    }
Cronix's avatar
Cronix
Best Answer
Level 67

He said to eager load the services relationship.

$bookings = Booking::with('services')->where(....)

Please or to participate in this conversation.