How can we create a multi-level laravel association

I have 4 tables. I want to implement a query in one table and get data from related tables.

In CakePHP we use contain, but in Laravel I have no idea.

  • country,
  • state
  • cities,
  • Places

Model code

class Country extends Model {
    public function states() {
        return $this->hasMany('App\State');
    }
}


class State extends Model {
    public function city() {
        return $this->hasMany('App\City');
    }
}


class City extends Model {
    public function location() {
        return $this->hasMany('App\Location');
    }
}

class Location extends Model {

}

I need to make a request in the Country, and I also want to get the state

$country = Country::where('id',1);
$country->states

Similarly, but how can I get cities -> locationwith this. Do I need to make another request manually? In CakePHP we use contain, but in Laravel there is no such keyword or functionality for this?

+4
source share
1 answer

That should do the trick I think

$country = Country::with('states.city.location')->where('id',1)->first();

id = 1, , ..

dd($country->toarray()); // to check the output

foreach foreach ..

Exemple

{{$country->name}}

@foreach($country->states as $state)
  {{$state->name}}
  @foreach($state->city as $city)
    {{$city->name}}
    @foreach($city->location as $location)
    {{$location->name}}
    @foreach
  @foreach
@foreach

: EAGER LOADING

+3

All Articles