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

bacordioroger's avatar

Displaying One to Many in Blade

This is my model

    public function getBookingDetails()
    {
        return $this->hasMany(BookingDetail::class,"booking_id","id");
    }

Controller

    public function showAllBookings(){
        $bookings = Booking::with('getBookingDetails')->get();
    
        return view('test_view_booking',compact('bookings'));
    }

Blade

@foreach($bookings as $booking)
    <td>{{ $booking->getBookingDetails->date_from->format('M d Y') }}</td>
    td>{{ $booking->getBookingDetails->date_to->format('M d Y') }}</td>

It says Property [date_from] does not exist on this collection instance.

It works with:

              <td>{{ $booking->getBookingDetails[0]->date_from->format('M d Y') }}</td>
              <td>{{ $booking->getBookingDetails[0]->date_to->format('M d Y') }}</td>

But only one data is shown.

This is my db: Booking

id|user_id|inventory_id
1|5|1

BookingDetails

id|booking_id|date_from|time_from|date_to|time_to
1|1|2019-03-18|15:30:00|2019-03-19|15:45:00
2|1|2019-04-18|15:30:00|2019-04-19|15:45:00

0 likes
2 replies
Sinnbeck's avatar

You have defined a hasMany relationship. This means that$ booking->getBookingDetails return a collection of detail instances, not just one.

Either look over all of your $booking->getBookingDetails (using another foreach) or change your relationship to a hasOne.

1 like
JohnBraun's avatar

A Booking has many BookingDetails, you probably want to loop over them in another foreach.

@foreach($bookings as $booking)
    @foreach ($booking->getBookingDetails as $detail)

         <td>{{ $detail->date_from->format('M d Y') }}</td>
         <td>{{ $detail->date_to->format('M d Y') }}</td>

    @endforeach
@endforeach

Please or to participate in this conversation.