Sandeep Sandeep - 8 months ago 23
MySQL Question

how can we make in laravel mutilevel association

I have 4 tables. I want to implement query on one table and getdata related tables. Please help me how can I do this. In cakphp we use contain but laravel I have no idea.


Model code
Country Model

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 make query on country and get state

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

like that but how can I get cities > location with this. May make another query manually? In cakephp we use contain, In lavavel no such these type of keyword in this?

Please help me


this should do the trick 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 citys ..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