Laravel RBAC 不同的行为

Laravel RBAC different behaviours

我正在将此 package 用于 laravel 5.2,当使用从控制器发送不同的结果进行查看时,我得到了不同的行为:

当我进行这样的查询时:

$users = User::all();

然后在我看来,我可以像这样检查用户角色:

@if($user->is('admin'))

这是预期的行为,但是当我发送这样的查询结果时:

$users = User::leftjoin('role_user', 'users.id', '=', 'role_user.user_id')
               ->orderBy(DB::raw('role_id IS NULL'))
               ->groupBy('users.id')
               ->orderBy('role_id')
               ->get();

我不能像我应该的那样检查,但我需要这样检查:

@if($user->role_id ==1)

最好在查询连接时添加 select 主 table:

$users = User::leftjoin('role_user', 'users.id', '=', 'role_user.user_id')
           ->select('users.*')
           ->orderBy(DB::raw('role_id IS NULL'))
           ->groupBy('users.id')
           ->orderBy('role_id')
           ->get();

那么在你看来:

@foreach($users as $user)
    @if($user->is('admin'))
         (...)
    @endif
@endforeach

如果这没有帮助,那么您必须检查 item 是什么类型。可能其他一些包会中断查询模型并返回 stdClass 而不是 User 模型。