How to Assign Role in Default AuthController

Published 1 year ago by Khudadad

I want to assign a role to user during sign up in Laravel default AuthController, so how to do this if anyone idea? Thanks users migration:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password', 60);
        $table->rememberToken();
        $table->timestamps();
    });
}

user_roles migration:

public function up()
{
    Schema::create('user_roles', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->integer('role_id');
        $table->timestamps();
    });
}

roles migration:

 public function up()
{
    Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name', 60);
        $table->text('description');
        $table->timestamps();
    });
}

register.blade:

    ......
    <div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}">
            <select name="role" id="role" class="form-control mb-10">
                <option value="" selected="selected">Select A Role</option>
                @foreach($roles as  $role)
                    <option value="{!! $role->r_id !!}">{!! $role->role_name !!}</option>
                @endforeach
            </select>
            @if ($errors->has('role'))
                <span class="help-block">
                    <strong>{{ $errors->first('role') }}</strong>
                </span>
            @endif
        </div>
willvincent

You ought to be able to handle this in the create method of the AuthController... app/Http/Controllers/Auth/AuthController.php

Something like this ought to work:

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

  $role = Role::findOrFail($data['role']);
  $user->roles()->save($role);

  return $user;
}

Please sign in or create an account to participate in this conversation.