Laravel nested relationships Laravel nested relationships laravel laravel

Laravel nested relationships


return Event::with('city.companies.persons')->get();

If you only want to select certain fields from the persons table, use this:

return Event::with(['city.companies.persons' => function ($query) {    $query->select('id', '...');}])->get();


For city and companies specific fields , you need to distribute the with eloquent.Eg:

return Event::with([    'city' => function ($query) {        $query->select('id', '...');    },    'city.companies' => function ($query) {        $query->select('id', '...');    },    'city.companies.persons' => function ($query) {        $query->select('id', '...');    }])->get();


return Event::with(['city:id,name', 'city.companies:id,name', 'city.companies.persons:id,name'])->get();