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?
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With