Reputation: 83
I use the standard mechanism authentication in Laravel 5.3 is built by command:php artisan make:auth
.
So, It have created controller RegisterController
with the following methods:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]));
}
So, I need to extend this method that to add data to related table for User table. For this I do:
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());
}
After this I get error:
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
Upvotes: 1
Views: 683
Reputation: 16181
I didn't use Laravel's auth logic, but it looks like the user gets logged in right after they're created. To log the user in Laravel needs the User object, hence:
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
The create()
method returns Model
. You, however, added attach()
to the return statement, and if you take a look at the API, the method returns void
which eventually translates to null
mentioned in the error message.
What you want to do, is something like this:
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;
}
Note: I assumed you have an id
column in your role(s)
table.
Upvotes: 3