How to assign role while registration in laravel

3.2k views Asked by At

I'm working in laravel and using spatie laravel-permission. So i want to assign some role while registration and user can choose it via radio-button. I've tried some solutions from similar topic Assigning the role while user registration But it return an error. Code and error text you can find down. Sorry for stupid question and grammar mistakies-i'm newbie in programminпg and english isn't my native language.

RegisterController (other code is default)

protected function create(array $data, Request $request )
{
    return $user=User::create([
        'name' => $data['name'],
        'patro' => $data['patro'],
        'surname' => $data['surname'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
                ]);
    $user->assignRole($request->input('role'));return $user;
}

register.blade.php (other code is default)

<select>
<option name="role">Teacher</option>
<option name="role">Student</option></select>

error

Too few arguments to function App\Http\Controllers\Auth\RegisterController::create(), 1 passed in C:\OpenServer\domains\uni\vendor\laravel\ui\auth-backend\RegistersUsers.php on line 34 and exactly 2 expected
1

There are 1 answers

20
Donkarnash On

Any statement after a return statement does not get executed

Remove the return statement in the create method before the statement to assign role and shift it to the end if you really want the return value to be the newly created user.

The error you are getting is because of event(new Registered($user = $this->create($request->all()))); in the register function of the Illuminate\Foundation\Auth\RegistersUsers trait.

Passing $request to the create method is not required because request data is already being passed as array $data so $data['role'] will be same as $request->input('role')

protected function create(array $data)
{
    $user=User::create([
        'name' => $data['name'],
        'patro' => $data['patro'],
        'surname' => $data['surname'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
                ]);

    //$user->assignRole($request->input('role'));
    $user->assignRole($data['role']);

    return $user;
}