首页 > 解决方案 > 尝试在 Laravel 8 中读取 null 的属性“权限”

问题描述

我正在尝试将用户注册到系统并默认分配患者角色。问题出现在 RegisterController 控制器中。在 create() 方法中,我编写了以下代码:

protected function create(array $data)
    {
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

        $role = \App\Models\Role::where('slug', 'paciente')->first();
        $permissions = $role->permissions;

        $user->roles()->attach($role);
        $user->permissions()->sync($permissions);

        return $user;
    }

laravel 8 抛出的错误如下:Attempt to read property "permissions" on null

它不能识别保存在 $ 权限变量中的角色的相关权限。解决办法是什么?

从已经非常感谢了!!!

标签: phplaravel-8

解决方案


正如我在评论中所说,您的数据库中似乎没有字段“slug”=“paciente”的“角色”。这就是为什么在这一行

$role = \App\Models\Role::where('slug', 'paciente')->first(); 

$role 为空。检查你的角色表


推荐阅读