Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - How to get Entrust Roles of a specific user

Tags:

php

laravel

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?

like image 534
PJunior Avatar asked Dec 26 '22 08:12

PJunior


2 Answers

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;
like image 72
Razor Avatar answered Jan 11 '23 06:01

Razor


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
like image 29
Mirsad Batilovic Avatar answered Jan 11 '23 06:01

Mirsad Batilovic