You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 6.0 Eloquent多对多关系查询问题求助

解决Laravel多对多关系中查询拥有指定角色的用户问题

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. The roles() 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 method users()) 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:

  • whereHas checks 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:30:20