Laravel - How to Get Trusted Roles for a Specific User

I do a little work with Laravel and using Zizaco Entrust .

During login as an administrator, I want to see all the Roles of a specific user.

I searched for a while but couldn’t find a hint ... How to do this using Entrust or will I use SQL queries?

+4
source share
2 answers

In your user class add

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

Then you can get all the roles for a specific user.

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

Zizaco\Entrust, . EntrustUserTrait. :

use EntrustUserTrait;

:

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

UserController ( ):

<?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'));
}

$user- > $users, $user- > role - , .

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

Source: https://habr.com/ru/post/1542669/


All Articles