我正在使用角色和权限种子程序:
class RolesAndPermissionsSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();
$permissions = [
'employers.index',
'employers.show',
'employers.create',
'employers.edit',
'employers.destroy',
];
foreach ($permissions as $permission) {
Permission::create(['name' => $permission]);
}
$role = Role::create(['name' => "Employer"]);
$role->givePermissionTo(Permission::all()->except(['employers.index', 'employers.destroy']));
}
}
当我创建一个新雇主时,会创建一个用户,并为其分配雇主角色:
class Employer extends Model
{
use HasFactory;
public function user()
{
return $this->belongsTo(User::class);
}
protected static function booted()
{
static::created(function ($employer) {
$employer->user->assignRole('Employer');
});
}
}
现在,在雇主测试中,我想使用以下权限:
class EmployerTest extends TestCase
{
use RefreshDatabase;
use WithFaker;
public function setUp(): void
{
parent::setUp();
$this->app->make(\Spatie\Permission\PermissionRegistrar::class)->registerPermissions();
$this->seed(RolesAndPermissionsSeeder::class);
}
public function test_permission()
{
$employer = \App\Models\Employer::factory()->create();
dump(Role::all()); // <-- shows all roles correctly
dump(Permission::all()); <-- shows all permissions correctly
dump(Role::where('name', 'Employer')->first()->permissions->pluck('name')->toArray()); // <-- shows the assigned permissions
dump($employer->user->hasRole('Employer')); // <-- shows true
dd($employer->user->getPermissionNames());
}
}
dd()
向items: []
展示了什么是意料之外的。我错过了什么?雇主的用户有雇主角色,但它没有权限,但角色本身有权限。这里出了什么问题?
1条答案
按热度按时间ccrfmcuu1#
根据文档,我认为您缺少的是
$employer->user->getAllPermissions()
:https://spatie.be/docs/laravel-permission/v5/basic-usage/role-permissions