mardi 25 août 2020

Laravel - Many To Many return child records filtered

I have a User model which has a M:M relationship with Role model (I use roles_user intermediate table for M:M relationship)

The intermediate table has a column "Active" which defines which of the multiple roles assigned to a User is the active one.

So, I'm trying to retrieve a User with all the relationships it has an also only the active role.

For that, Im executing the follwing code https://laravel.com/docs/6.x/eloquent-relationships#querying-relationship-existence :

public function index()
    {    
        $users = User::whereHas('roles', function (Builder $query) {
            $query->where('active', true); 
        })->get();            
        foreach ($users as $user) {
            dd($user->roles);
        }
        
        return view('pages.admin.users.index', compact('users'));
    }

When I dd the collection, I have the 5 records in intermnediate table and not just the active one wich I'm filtering:

enter image description here

enter image description here

What I am doing wrong?

Regards



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire