简体   繁体   English

Laravel - 如何获得特定用户的Entrust角色

[英]Laravel - How to get Entrust Roles of a specific user

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 Roles of a specific user. 以管理员身份登录时,我希望查看特定用户的所有角色

I'v searched for a while but didn't find any clue... How can I do it using Entrust or shall I use SQL queries? 我搜索了一段时间,但没有找到任何线索......我怎样才能使用Entrust或者我会使用SQL查询?

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;

If you are using Zizaco\\Entrust you don't need new roles method in User model. 如果您使用的是Zizaco \\ Entrust,则在用户模型中不需要新的角色方法。 Roles method already exist in EntrustUserTrait class. 角色方法已存在于EntrustUserTrait类中。 You only need this line inside User class: 你只需要User class中的这一行:

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->在$ users循环中的角色因为$ user-> roles是集合,即使用户只有一个角色。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM