Home > Enterprise >  Laravel Mass assignment fill() method skipping one value
Laravel Mass assignment fill() method skipping one value

Time:08-18

Problem: Assignment of "role_id"

Code:

function register(Request $request){
        $validated = $request->validateWithBag('ers', [
            'email'=>'required',
            'password'=>'required|min:6',
            'role_id'=>'integer',
            'name'=>'required',
        ]);

        $user = new User;
        $user->fill($validated);
        // $user->role_id = $request->role_id;
        $user->save();

        return response("Saved record");
    }

What I have tried:

  1. renamed role_id to roleid
  2. when I uncomment the manually $user->role_id = $request->role_id that works but I am wondering why isn't fill() doing that for me.

Value's coming from:

<select  name="role_id">
    <option value=1>Standard Customer</option>
    <option value=2>Doctor</option>
    <option value=3>Distributor</option>
</select>

Note that

  • The database schema of users has role_id datatype integer (if this info is relevant)
  • dd($request->all()) has role_id being passed
  • dd($validated) also shows me role_id in array
  • all 3 values except role_id is caught except role_id
  • I get error that role_id isn't assigned value and the generated query below:
insert into
  `users` (
    `email`,
    `password`,
    `name`,
    `updated_at`,
    `created_at`
  )
values
  (
    [email protected],
    password123,
    Imran Ahmad,
    2022 -08 -17 05: 11: 34,
    2022 -08 -17 05: 11: 34
  )

Let me know if you want me to show you something further.

CodePudding user response:

fill() is one of the mass assignment functions. In order to prevent mass-assignment vulnerability, in your model you should define which model attributes you want to make mass assignable. You may do this using the $fillable property on the model. Make sure role_id is in that list.

If you would like to make all of your attributes mass assignable, you may define your model's $guarded property as an empty array. If you choose to unguard your model, you should take special care to always hand-craft the arrays passed to Eloquent's fill, create, and update methods.

See more docs here.

  • Related