php - 尝试在 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
它不能识别保存在 $ 权限变量中的角色的相关权限。解决办法是什么?
从已经非常感谢了!!!
解决方案
正如我在评论中所说,您的数据库中似乎没有字段“slug”=“paciente”的“角色”。这就是为什么在这一行
$role = \App\Models\Role::where('slug', 'paciente')->first();
$role 为空。检查你的角色表
推荐阅读
- python - 如何从我在 Python 中创建的文件中导入模块?
- javascript - 将 Axios 添加到 React 图表并获取 JSON 数据
- matlab - fmi2Instantiate:未定义的函数或变量“fmuhelper”
- awk - 如何从文件的一部分写入字符串和比列?
- firebase - Firebase 云函数多次执行
- sql - 如何获得不同的记录?
- node.js - 如何从猫鼬内部调用 req.flash() ?
- javascript - Vue 单元测试:使用错误导入组件的函数
- python - 将 2D 数组元素插入 3D 数组 Python
- javascript - JavaScript:将没有时区的时间戳转换为毫秒