WLFCRK WLFCRK - 2 months ago 18
MySQL Question

Laravel 5 nested relation with condition

I've these tables:







I need to grab all Users where slug is for example 'leader'

How can I do it?

What I got so far:

class clan extends Model{
public function leader()
$leader = User::whereHas('role', function($query) {
$query->where('slug', 'leader');
})->where('clan_id', $this->id)->get();

return $leader;

But this wouldn't be smart. Instead of this I would like to have it joined my clans table



so I can access it easily.

Thanks alot :)


You can create a one-to-many relations between clan and user as:

public function users()
    return $this->hasMany('App\User');

And in your leader() function you can write as:

public function leader() 
    $leader = $this->users()->whereHas('role', function($query) {
        $query->where('slug', 'leader');

    return $leader;


To the response of comment below

You can create a scope as:

public function scopeLeader($query)
    return $query->with(['users' => function($query) {
               $query->whereHas('role', function($q) {
                    $q->where('slug', 'leader');

And You can fetch Clan as:

Clan::where('name', $clanname)->leader()->get()