I have a relationship in my app where a organisation can have many users and many users can have many organisations, in my model this looks like this,
Organisation.php
public function users() {
return $this->belongsToMany('User')->withPivot('is_admin');
}
User.php
public function organisations() {
$this->belongsToMany('Organisation');
}
What I am wanting to do, is run a query that has multiple where clauses and then return the row data and any pivot data.
For one where clause I would do the following,
$org = Organisation::find(1);
$orgUsers = $org->users()
;
What I cannot figure out is how I would user multiple wheres if I needed too?
Assuming you want to add the wheree()
's to users, it might look something like this (Eager loading the users)
$constraints = ['fname' => 'john', 'lanme' => 'doe'];
$org = Organisation::with(['users' => function($query) use ($constraints){
foreach($constraints as $field => $val)
$query->where($field, $val);
// Or if you just want admin users using your pivot table field
$query->pivot->where('is_admin', true);
}])->find($id);
Or, you could get them all, and filter them if you need a collection of users, and a collection of admins
$org = Organisation::with('users')->find($id);
$admins = $org->users->filter(function($user){ return $user->pivot->is_admin });