4
votes

I am using Laravel 5.2 and Zizaco/entrust 5.2,my question is:
How to get the role of current user when using Zizaco/entrust?

NameAndRole.php

namespace App\Services;

use App\User;
use App\Role;
use Zizaco\Entrust\EntrustRole;
use Illuminate\Support\Facades\Cache;

class NameAndRole
{
    public $username;
    public $role;

    public function __construct() {
        $user = \Auth::user();
        $this->username = $user->name;
        $this->role =$user->roles->first()->name;
    }
}

Models:

Role:https://github.com/Zizaco/entrust#role

<?php namespace App;

use Zizaco\Entrust\EntrustRole;

class Role extends EntrustRole
{
}

User:https://github.com/Zizaco/entrust#user

<?php

use Zizaco\Entrust\Traits\EntrustUserTrait;

class User extends Eloquent
{
    use EntrustUserTrait; // add this trait to your user model

    ...
}

view: sidebar.blade.php

@inject('details','App\Services\NameAndRole')
{{ $details->username }}
{{ $details->role }}

error:

ErrorException in NameAndRole.php line 20:
Trying to get property of non-object (View: D:\wnmp\www\laravel-entrust\resources\views\employer\partials\sidebar.blade.php) (View: D:\wnmp\www\laravel-entrust\resources\views\employer\partials\sidebar.blade.php)
2

2 Answers

16
votes

You can access it like any other relationship in eloquent. So to access the roles of a user you can do:

$user->roles

This returns an eloquent collection as a User can have many Roles (i.e. it won't be just one), so if you're only expecting one role and you want the string value of it, you could do:

$user->roles->first()->name // or display_name

I guess you could cast it to an array using toArray() method, if you wanted to work with an array instead:

$user->roles->toArray()

Edit

You could check the user has a role before assigning it:

$this->role = $user->roles ? $user->roles->first()->name : 'No role';
0
votes

To get the roles id field:

$user->roles->first()->id;