Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

integreatmedia's avatar

Update model using associative form array

I have created a Laravel form which is a table which pulls multiple rows from the database, I now need some advise on how best to update these records when the save button is pressed on the form..

In this example I have two rows in my table, which if I print_r the array I see: Array ( [1001] => Array ( [activity] => 20 [location] => 4 [time] => 13 [duration] => 9 [days] => 1 ) [1002] => Array ( [activity] => 2 [location] => 1 [time] => 25 [duration] => 5 [days] => 1 ) )

1001 and 1002 are the Ids of the records in the table.

How is best to update this with eloquent please? I assume I need to loop through in some way and do an update for each?

0 likes
5 replies
Gog0's avatar

maybe something like this:

foreach ($collection as $element_id => $element_data){
    $myElement = MyModel::find($element_id);
    $myElement->fill($element_data);
    $myElement->save();
}

Edit: also I think you would need to be sure your attributes are part of the fillable attributes of your model by adding

protected $fillable = ['activity', 'location', 'time', 'duration', 'days'];

to your model.

integreatmedia's avatar

Thanks @Gog0 - is the best way to get the 'collection' from the form using;

$collection = array_except(Input::all(), '_method');

or should I be using something else?

Gog0's avatar

@integreatmedia don't really know how your form is done here but your inputs should come as an array by using the same name attribute, for example name="mycollectionname[1001][activity].

You would then just use

$collection = $request->input('mycollectionname');

I prefer using dependency injection by adding Request $request to the controller method parameters and use Illuminate\Http\Request; to the controller instead of using the Input Facade, as suggested by @balistikbill

Also you could use update() as suggested by @ejdelmonico

foreach ($collection as $element_id => $element_data){
    MyModel::where('id', $element_id)
                  ->update($element_data);
}

Sounds actually more relevant as you don't really need to retrieve your entity before updating it. Just keep in mind that if you make use of saved and updated events on your model they would not be fired that way.

1 like

Please or to participate in this conversation.