Search code examples
phplaravellaravel-5laravel-collection

laravel how to get all nested relation to a collection


So lets say i have a post which belong to 1 user which belong to 1 group;

now I getting all the posts:

$posts = Post::inCategory(1)->with('user','user.group')->get();

now I need to see all groups in the above query, is there some simple 1 liner collection trick to extract them? without looping like:

$groups = [];
foreach ($posts as $post){
 $groups[] = $post->user->group;
}

Solution

  • You can use pluck method,

    $groups = Post::inCategory(1)->with('user','user.group')->get()->pluck('user.group')->all()