![](/img/trans.png)
[英]Laravel add user and role using zizaco confide and entrust
[英]Laravel 5.2 : How to get the role of current user when using `Zizaco/entrust`?
我使用的是Laravel 5.2和Zizaco/entrust
5.2,我的問題是:
如何在使用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;
}
}
楷模:
角色: https : //github.com/Zizaco/entrust#role
<?php namespace App;
use Zizaco\Entrust\EntrustRole;
class Role extends EntrustRole
{
}
用戶: 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
...
}
查看: sidebar.blade.php
@inject('details','App\Services\NameAndRole')
{{ $details->username }}
{{ $details->role }}
錯誤:
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)
您可以像雄辯中的任何其他關系一樣訪問它。 因此,要訪問用戶的角色,您可以執行以下操作:
$user->roles
這會返回一個雄辯的集合,因為User
可以擁有多個Role
(即它不會只有一個),所以如果你只想要一個角色而你想要它的字符串值,你可以這樣做:
$user->roles->first()->name // or display_name
我猜你可以使用toArray()
方法將它toArray()
轉換為數組,如果你想使用數組:
$user->roles->toArray()
編輯
您可以在分配之前檢查用戶是否有角色:
$this->role = $user->roles ? $user->roles->first()->name : 'No role';
要獲取角色id
字段:
$user->roles->first()->id;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.