I have an entity Set that has many Items in it. So, when updating the sets, the form includes the field to update it's item too. I've done it and it's working well, but I'm not sure if it's the correct and most efficient/elegant way to do it. Here's my code:
$set->fill(Input::all());
foreach (Input::get('course') as $course_id => $content) {
$item = $set->items->filter(function ($item) use ($course_id) {
return ($item->course_id == $course_id);
})->first();
$item->content = $content;
$set->items()->save($item);
}
$set->save();
As you can see, for each items, I looped through all the input (which may vary on how many it has), filter it, and save the value 1 by 1. So a query is executed for every iteration. I use filter so that it doesn't have to do a query for every check.
So my question is, is there a more efficient/elegant way to do this? Something like saveMany() maybe?
You can use the method saveMany like this:
$set->fill(Input::all());
$items = array();
foreach (Input::get('course') as $course_id => $content) {
$item = $set->items->filter(function ($item) use ($course_id) {
return ($item->course_id == $course_id);
})->first();
$item->content = $content;
$items[] = $item;
}
$set->items()->saveMany($items);
$set->save();
As pointed in related models of laravel docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With