Search code examples
laravel-bladelaravel-8eloquent-relationship

Nested relationship access with Laravel 8


This is the problem. I have a booking table. It's properties are as follows

   -id
   -path_id
   -start_time

The path table is as follows

-id
-car_id
-fare
-start_location
-end_location

the car table

-id
-plate_number
-year_of_manufacture
-model

I have a Laravel application where the booking details need to be displayed. The models have the relations described as

BookingDetails model:

public function car()
    {
        return $this->belongsTo(Car::class);
    }

    public function path()
    {
        return $this->belongsTo(Path::class);
    }

The controller gets the details with,

BookingDetails:with('route')->get();

I know I can use an if statement with the above and get the car plate number. But is there a way I can get it with relations in Laravel?

Thanks.


Solution

  • I think you have failed to improvise here. Did you try this?

    Assuming what you need is the car plate number,

    You could,

    $details = BookingDetails:with('route')->get();
    

    in the blade,

    $details->route->car->plate_number
    

    Check this and reply. And don't forget to mark as answer if found useful.