Laravel - 如何获取特定用户的委托角色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23958288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:34:58  来源:igfitidea点击:

Laravel - How to get Entrust Roles of a specific user

phplaravel

提问by PJunior

I'm making a small work with Laravel and using Zizaco Entrust.

我正在用 Laravel 做一个小工作,并使用Zizaco Entrust

While logged in as Administrator I want to see all Rolesof a specific user.

以管理员身份登录时,我想查看特定用户的所有角色

I'v searched for a while but didn't find any clue... How can I do it using Entrustor shall I use SQL queries?

我已经搜索了一段时间,但没有找到任何线索......我该如何使用Entrust或者我应该使用 SQL 查询?

回答by Razor

In your User class add

在您的 User 类中添加

public function roles()
{
    return $this->belongsToMany('Role','assigned_roles');
}

Then you can get all roles for a specific user

然后您可以获得特定用户的所有角色

$user = User::with('roles')->find(1);
$roles = $user->roles;

回答by Mirsad Batilovic

If you are using Zizaco\Entrust you don't need new roles method in User model. Roles method already exist in EntrustUserTrait class. You only need this line inside User class:

如果您使用的是 Zizaco\Entrust,则不需要用户模型中的新角色方法。Roles 方法已存在于 EntrustUserTrait 类中。您只需要 User 类中的这一行:

use EntrustUserTrait;

like this:

像这样:

<?php
namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;

class User extends Authenticatable
{
    use EntrustUserTrait; // add this trait to your user model
            .....
}

In your UsersController you can select users with their roles (index method):

在您的 UsersController 中,您可以选择具有角色的用户(索引方法):

<?php
namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;

class UsersController extends Controller
{
    protected $users;

public function __construct(User $users)
{
    $this->users = $users;
    parent::__construct();
}

public function index()
{
    $users = $this->users->with('roles')->paginate(25);
    return view('users.index', compact('users'));
}

In your blade loop $user->roles inside $users loop because $user->roles are collection even if user have only one role.

在您的刀片循环 $user->roles 内 $users 循环中,因为即使用户只有一个角色, $user->roles 也是集合。

@foreach($users as $user)
    @foreach($user->roles as $role)
        {{ $role->display_name }}
    @endforeach
@endforeach