[英]Cannot use `roles` method default of Laravel Permission Spatie
我安裝了 spatie/laravel-permission,但我不能使用spaite
role
方法默認值。 在User
模型中,我添加了HasRoles
:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use HasApiTokens, HasFactory, Notifiable, HasRoles;
const ACTIVE = 'active';
const LOCKED = 'locked';
/**
* The attributes that are mass assignable.
*
* @var string[]
*/
protected $fillable = [
'name',
'username',
'status',
'email',
'password',
'password_updated_at'
];
/**
* The attributes that should be hidden for serialization.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
// public function roles(): BelongsToMany
// {
// return $this->belongsToMany(\App\Models\Role::class, 'user_has_roles', 'user_id');
// }
public function getJWTIdentifier() {
return $this->getKey();
}
public function getJWTCustomClaims() {
return [];
}
}
如果我定義了 spatie 的新roles
方法覆蓋方法(評論部分),我將從代碼中獲取角色:
\App\Models\User::find(1)->first()->roles()->get()->toArray()
結果是:
array:1 [
0 => array:6 [
"id" => 1
"name" => "admin"
"guard_name" => "api"
"created_at" => "2021-10-19T18:23:20.000000Z"
"updated_at" => "2021-10-19T18:23:20.000000Z"
"pivot" => array:2 [
"user_id" => 1
"role_id" => 1
]
]
]
但是如果我使用下面的 spatie 代碼的roles
方法默認值,則不是結果,這是我運行時的結果:
[]
找了很多都沒有結果,希望有人能幫幫我,謝謝。
Spatie Laravel 權限不使用roles
方法。
正確的方式:
$roles = $user->getRoleNames(); // Returns a collection
文檔: https : //spatie.be/docs/laravel-permission/v5/basic-usage/basic-usage
P/s: Anh em cần hỏi thêm gì thì cứ gửi tin nhắn。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.