0

I am trying to add a custom field 'role' to Laravel 5.3 User Auth. The role will determine whether the user is admin amongst other roles and so because the Auth scaffolding uses mass assignable attributes, there is a vulnerability.

Therefore I have changed my User model to:

protected $guarded = [
  'role'
];

RegisterController I have added my custom fields (a default user will have the role = customer);

   return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'facebook_id' => $data['facebook_id'],
        'linkedin_id' => $data['linkedin_id'],
        'avatar' => $data['avatar'],
        'token' => $data['token'],
        'role' => 'customer',

I am getting this error message:

SQLSTATE[HY000]: General error: 1364 Field 'role' doesn't have a default >value (SQL: insert into users (name, email, password, >facebook_id, linkedin_id, avatar, token, updated_at, >created_at) values (name, [email protected], hashed password, , , , , >2017-01-20 17:21:16, 2017-01-20 17:21:16))

Can't for the life of me figure it out.

I was thinking that maybe I don't use the mass assignable input, but I have a feeling that may mess up the rest of the Auth scaffold.

Thanks for any help

2 Answers 2

1

An easy way to set the default role is to actually define it in the model

class User extends Model
{
    protected $attributes = [
        'role' => 'customer',
    ];

    protected $guarded = [
      'role'
    ];
    //...

Now when you use the create method and don't pass the the 'role' attribute, the insert will use the value 'customer'

Sign up to request clarification or add additional context in comments.

2 Comments

OK thanks, I understand how this works, I am still a bit confused as to why my initial method fails though..! Cheers
the whole point of guarded is you can not pass create(['role'=>'foo'])
0

In your migration for the users table where you add the role field, you either need to set the field as nullable, or give it a default value, so that when you mass assign without it, the database knows how to deal with that field.

Schema::table('users' function(Blueprint $table){
  $table->string('role')->default('customer');
});

or

Schema::table('users' function(Blueprint $table){
  $table->string('role')->nullable();
});

if your code can deal with a null role value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.