mangonights
mangonights

Reputation: 979

How to: mass assign an update in Laravel 4?

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.

Upvotes: 29

Views: 22145

Answers (4)

Nam Tiến Nguyễn
Nam Tiến Nguyễn

Reputation: 11

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

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

Upvotes: 1

Phill Sparks
Phill Sparks

Reputation: 20879

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

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

Upvotes: 51

Kieran Fahy
Kieran Fahy

Reputation: 33

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

Upvotes: 1

user2920996
user2920996

Reputation:

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

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

Upvotes: 20

Related Questions