Search code examples
laravellaravel-5entity-relationship

Laravel get all related models for multiple models


I have a users table and a groups table. I have set up a many to many users/groups relations. When I run

$users = User::where("id",'=',6)->first()->groups;

,I get the right group.

But I will have cases where my queries will take in an array of users. How do I get all the groups of all those users using laravel relationships ?


Solution

  • eMAD's suggestion does not work because Laravel only allows relationship functions to be execute on objects and not array of objects. What you want harvey is a concept called eager loading.

    $users = User::whereIn('id', [6, 7, 8])->with('groups')->get();
    

    By using this code, you will be able to access $user->groups->someInfo in your code. Happy coding