Search code examples
laravellaravel-5.3

How do I modify my Laravel 5.2 registration to assign new users a role in Laravel 5.3?


I'm new to Laravel, and have been trying to build a user-role authentication system. As 5,3 is very new, there are not many resources that are beginner-friendly. I am using the authentication system created by php artisan make:auth, however I am unsure on how to associate my newly created users with a my roles table.

Initially I had been following this video series on YouTube, but the Authentication controllers differ greatly between 5.2/5.3

I'm hoping that someone can help me figure out what must be done to add in an equivalent what is done in the video to the new controller.

Laravel 5.2 Role Association

public function postSignUp(Request $request)
{
    $user = new User();
         . . .
    $user->save();
    $user->roles()->attach(Role::where('name', 'User')->first();
}

From Laravel 5.3 RegisterController.php

protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }

Thanks for reading.


Solution

  • You can modify the auto-generated Controllers:

    protected function create(array $data)
    {
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    
        $user->roles()->attach(Role::where('name', 'User')->first());
    
        return $user;
    }