Sandeep Sandeep - 5 months ago 19
PHP Question

How can we make a laravel multilevel association

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

In CakePHP, we use

contain
but in Laravel I have no idea.


  • countries,

  • states,

  • cities,

  • locations



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 have to make a query on Country and I want to also retrieve the State

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


Like that, but how can I get
cities -> location
with this. Do I need to make another query manually? In CakePHP we use
contain
, but in Laravel, there is no similar keyword or functionality to this?

Answer

This should do the trick I guess

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

You will get the country of id = 1 and it's states, and each of it's states will have the cities etc

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

Then use a foreach loop to fetch the states and another foreach loop inside it to fetch the cities etc

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

Check Docs for more info : EAGER LOADING