php Laravel 5.2:使用`Zizaco/entrust` 时如何获取当前用户的角色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36719279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:53:44  来源:igfitidea点击:

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

phplaravel

提问by zwl1619

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

我正在使用 Laravel 5.2 和Zizaco/entrust5.2,我的问题是:
如何在使用时获取当前用户的角色Zizaco/entrust

NameAndRole.php

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

角色:https: //github.com/Zizaco/entrust#role

<?php namespace App;

use Zizaco\Entrust\EntrustRole;

class Role extends EntrustRole
{
}

User:https://github.com/Zizaco/entrust#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

视图: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)

回答by haakym

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

您可以像 eloquent 中的任何其他关系一样访问它。因此,要访问用户的角色,您可以执行以下操作:

$user->roles

This returns an eloquent collection as a Usercan 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:

这将返回一个 eloquent 集合,因为 aUser可以有多个Roles(即它不会只有一个),所以如果您只期待一个角色并且您想要它的字符串值,您可以这样做:

$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:

我想你可以使用toArray()方法将它转换为数组,如果你想使用数组来代替:

$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';

回答by Bharath N

To get the roles idfield:

要获取角色id字段:

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