Laravel - How to get Entrust Roles of a specific user

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

I'm making a small work with Laravel and using 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?

回答1:

In your User class add

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;


回答2:

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:

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):

<?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.

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!