我在Laravel 5.3中使用标准机制认证是通过命令构建的:RegisterController
。
因此,它使用以下方法创建了控制器 protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]));
}
:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
])->roles()->attach(Role::where('name', "admin"))->first());
}
所以,我需要扩展这个方法,将数据添加到User表的相关表中。为此我做了:
FatalThrowableError in SessionGuard.php line 441:
Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given, called in \vendor\laravel\framework\src\Illuminate\Foundation\Auth\RegistersUsers.php on line 32
在此之后我收到错误:
{{1}}
答案 0 :(得分:3)
我没有使用Laravel的auth逻辑,但看起来用户在创建后立即登录。要在Laravel中记录用户需要User对象,因此:
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
create()
方法returns Model
。但是,您已将attach()
添加到return语句中,如果您查看API,则returns void
方法最终会转换为错误中提到的null
消息。
你想做什么,是这样的:
protected function create(array $data) {
// Create the User and store the object
$newUser = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
// Add extra data
$adminRole = Role::where('name', 'like', 'admin')->first();
$newUser->roles()->attach($adminRole->id);
// Return the new User object
return $newUser;
}
注意:我假设您的id
表格中有role(s)
列。