Wednesday, March 15, 2017

Laravel eager load through pivot?

I'm trying to eager load some data through an id in a pivot table.

Right now I've just done it manually but wondering if there is a way to do this directly through eloquent with a relation?

$ids = $tournament->matches
                  ->pluck('users')
                  ->flatten()
                  ->pluck('pivot')
                  ->pluck('team_id')
                  ->unique();

$teams = \App\Models\Team::whereIn('id', $ids)->get()->keyBy('id');

$tournament->matches->each(function ($match) use ($teams) {
    $match->users->each(function ($user) use ($teams) {
        $user->team = @$teams[$user->pivot->team_id] ?: null;
    });
});



via Rob

Advertisement