Filter pivot table data using Laravel models

Let's say I have three tables (this is just an example):

users user_id username roles role_id name user_roles user_id role_id primary (boolean) 

And the corresponding laravel models:

  class User extends Eloquent { public function roles() { return $this->belongsToMany('Role')->withPivot('primary'); } } class Role extends Eloquent { public function users() { return $this->belongsToMany('User')->withPivot('primary'); } } 

I want to get a list of all users, but only with primary roles in the returned object. If I use something like:

 $users = User::with('roles')->find(1); 

Each user object will have a list of all its corresponding roles. I want this list to contain only the main roles. Is there a way to do this from the request, without further processing the $ users array?

+7
php pivot-table eloquent filtering laravel
source share
2 answers

Try the following:

 $users = User::with(array('roles' => function($query) { $query->where('primary', 1); }))->find(1); 
+8
source share

I suggest you create an additional method in your user model as follows:

 public function primaryRoles() { return $this->roles()->wherePivot('primary', true); } 

Then use something like:

 $users = User::with('primaryRoles')->find(1); 

In addition, in the documentation section, the "Load Limitations" section may be relevant.

+13
source share

All Articles