John Davidson

php - Laravel Mass assignment fill() method skipping one value

0 comments
Message:


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 class="input100" 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.



My Answer:
values using the fill() method in Laravel is skipping one value.

Solution: This issue can occur if the value being skipped is a guarded attribute in the model. Guarded attributes are those that cannot be mass assigned using the fill() method. To resolve this issue, you can either remove the attribute from the guarded array in the model or use the forceFill() method instead of fill() to assign the value.

Here is an example of how to use the forceFill() method:

php
$data = [
'attribute1' => 'value1',
'attribute2' => 'value2',
'attribute3' => 'value3',
];

$model->forceFill($data);


By using forceFill(), you can assign all values to the model, including those that are guarded.

Rate this post

5 of 5 based on 8331 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us