Search code examples
phpmysqlregistrationroleslaravel-6

Assigning user role upon registration in laravel issue


In my laravel application i'm trying to assign user role upon the registration. Following is my RegistrationController

protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'last_name' => $data['last_name'],
            'email' => $data['email'],
            'mobile'=>$data['mobile'],
            'username'=>$data['username'],
            'password' => Hash::make($data['password']),
            'propic'=>'user-pic.png',
            'user_roles' =>'customer',
        ]);

        $lastdata = DB::table('users')->orderBy('id', 'desc')->first();
        $last_id=$lastdata->id;

        $user= User::where('id','=',$last_id)->firstOrFail();
        $user->assignRole('customer');
    }

But when I run the code user get created, activation mail has been sent but the role is not assigning! how can i fix that and where am I doing wrong?


Solution

  • There are a few things you might want to consider.

    1) your function won't proceed further after the return statement. You are creating a user with a return statement hence your code below of that won't execute. I'll recommend storing the return object into some variable.

    // let's say
    $user =  User::create([
                'name' => $data['name'],
                'last_name' => $data['last_name'],
                'email' => $data['email'],
                'mobile'=>$data['mobile'],
                'username'=>$data['username'],
                'password' => Hash::make($data['password']),
                'propic'=>'user-pic.png',
                'user_roles' =>'customer',
            ]);
    // then you can simply get it's value by 
    $user_id = $user->id; // you won't need to query last added row's value.
    

    2) If the user role is not getting saved into your database then check if you have assigned that 'user_roles' field as fillable into User model.