Search code examples
laravel-8laravel-jetstream

How can assign role to registered user using laravel 8 +jetstream + spatie


I've created roles using spatie. I want to let jetstream register form assign role 'gust' to any user registered via jetstream register form.


Solution

  • I figured it out by going to: app>actions>Fortify>CreateNewUser.php>

    public function create(array $input)
        {
            Validator::make($input, [
                'name' => ['required', 'string', 'max:255'],
                'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
                'password' => $this->passwordRules(),
            ])->validate();
    
            return DB::transaction(function () use ($input) {
                return tap(User::create([
                    'name' => $input['name'],
                    'email' => $input['email'],
                    'password' => Hash::make($input['password']),
                ]), function (User $user) {
                    $this->createRole($user);
                });
            });
        }
    
    

    then I've created a protected function createRole as follows:

    protected function createRole(User $user)
        {
            $user->assignRole('geust');
        }
    

    Which automatically assign a role to newly registered user. don't forget to add the following directives to the top of the file:

    use Spatie\Permission\Models\Role;
    use Spatie\Permission\Models\Permission;
    

    Second directive in case if you want to assign a permission as well.