Sandeep Sandeep - 1 year ago 77
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

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);

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

Answer Source

This should do the trick I guess

$country = Country::with('')->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



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

Check Docs for more info : EAGER LOADING

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download