How to: mass assign an update in Laravel 4?
Asked Answered
O

4

28

This is an for internal app, mass assignment security is not an issue in this case.

I'm dealing with very large (numerous) form fields, so mass assigning the user edits would be great. Mass assignment seems to work fine with 'create()' but not with doing a find & save.

This is what I have:

$post_data = Input::all();
$formobj = HugeForm::find($id);
$formobj->save($post_data);

How do I go about it? I'd rather not specify many dozens of form inputs.

Outoftheway answered 12/6, 2013 at 22:3 Comment(0)
O
51

You should be able to use fill(array $attributes)...

$post_data = Input::all();
$formobj = HugeForm::find($id);
$formobj->fill($post_data);
$formobj->save();
Oke answered 12/6, 2013 at 22:9 Comment(2)
It's still in the API docs for 5.2, there's a lot that's not covered in the basic documentation, perhaps you could recommend to the maintainers that this be added?Oke
Thank you brother Phill, this solution still works on Laravel 10.Huberman
T
20

In case of mass update it could be written even shorter.

$post_data = Input::all();
HugeForm::find($id)->update($post_data);
Tyrus answered 25/10, 2013 at 17:45 Comment(1)
update won't create new records whereas the save method will create a new row if it doesn't already exist and update the existing ones.Lightman
J
1

To allow mass assignment within Laravel you need to add:

protected $guarded = array();

Into your model. Basically this tells laravel not to protect any fields, you could also use:

protected $fillable = array();

And then set the fields you want to be fillable.

Hope this helps

Jameejamel answered 19/11, 2013 at 22:54 Comment(0)
W
1

This worked for me just 1 line (Laravel 8):

#ModelName::find($id)->update($request->all());

Wards answered 25/10, 2020 at 18:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.