Apologies in advance if this is trivial, I am learning Laravel.
I have a simple hasMany relationship for 'Companies' and 'Users'. i.e. each company has users.
public function users()
{
return $this->hasMany(User::class);
}
I am trying to limit the users by only those with the role 'users' (which is the same as: users without the role 'admin').
I am trying to write the relationship to filter this, but am wondering if this is possible with table joins?
public function users()
{
return $this->hasMany(User::class)->[SOMETHING HERE TO LIMIT RESULTS BY ROLE];
}
Thanks
Try:
return $this->hasMany(User::class)->role('user');
Fantastic, thank you!
Can see in DebugBar that it has constructed the database queries all nicely for me.
Just what I was hoping was possible, and so clean and obvious when you know how. Thank you for the help.
For sure.
FYI - that's just a "scope". Albeit the logic is a little more complex than you're probably used to. You can see the code for it here:
So clever. Laravel makes it so clean. Thanks for the learning opportunity!
Most helpful comment
Try: