1

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
0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.