Laravel 6.0 Eloquent多对多关系查询问题求助
Hey there! Let's sort out this issue step by step. Your controller code has a small logical error right now—let's break down what's wrong and fix it.
问题所在
Your current line $users = Role::all()->roles()->where('name', 'ADMIN'); won't work because:
Role::all()returns a collection of all Role models, not a single Role instance. Theroles()method is defined on individual Role models, not collections.- Even if you fixed that, the logic is backwards: you're trying to call
roles()on a Role collection, but you want users associated with the ADMIN role.
解决方案1:通过Role模型关联查询用户
This approach first fetches the ADMIN role, then pulls all users linked to it via the many-to-many relationship:
public function index($type) { // Fetch the ADMIN role first, then get its associated users $adminRole = Role::where('name', 'ADMIN')->first(); // Add a check to avoid errors if the role doesn't exist $users = $adminRole ? $adminRole->users : collect(); return view('admin.user.list', compact('users')); }
Why this works:
Role::where('name', 'ADMIN')->first()gets the single Role model for the ADMIN role.- Accessing
$adminRole->users(using the property, not the methodusers()) automatically executes the relationship query and returns a collection of User models linked to this role.
解决方案2:通过User模型过滤关联角色(更灵活)
If you need to add more filters for users later (like active status, etc.), using whereHas on the User model is a better approach:
public function index($type) { $users = User::whereHas('roles', function ($query) { // Filter users who have a role named ADMIN $query->where('name', 'ADMIN'); })->get(); return view('admin.user.list', compact('users')); }
Why this works:
whereHaschecks that the User has at least one related Role model that matches the condition inside the closure. This is great for combining with other User query constraints (e.g.,->where('active', true)).
视图中显示用户
Once you pass the $users collection to your view, you can loop through them like this:
@foreach($users as $user) <div class="user-item"> {{ $user->name }} {{ $user->lastname }} </div> @endforeach
额外提示
Your model relationship code looks correct! Just a quick note:
- In your User model, you specified
'role_user'as the pivot table name, which is correct. - In your Role model,
belongsToMany(User::class)works without specifying the pivot table because Laravel automatically uses the alphabetical combination of the model names (role_user), which matches your table.
内容的提问来源于stack exchange,提问作者carlos sierra garcia

