Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2 : How to get the role of current user when using `Zizaco/entrust`?

Tags:

php

laravel

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)
like image 559
zwl1619 Avatar asked Dec 04 '22 01:12

zwl1619


1 Answers

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';
like image 131
haakym Avatar answered May 04 '23 00:05

haakym