Search code examples
phplaraveleloquent-relationship

Updating multiple Eloquent models with different values


I have a Parent model with a hasMany relationship to a Child model. I would like to update a single property in each child with a specific and different value. How can I do this?

I know I can use mass assignment to update the property in each child with the same value, i.e.

Parent::findOrFail($id)->children()->update(["property"=>"new value"])

But how do I do this with individually set values? e.g. if my Parent has 4 children I would like to set it with something like this

Parent::findOrFail($id)->children()->update(["property"=>[1,2,3,4]])

And then child one would have 1, child two has 2 etc.


Solution

  • Something like this should work, looping over the relationship collection:

    $values = [1, 2, 3, 4];
    $parent
        ->children
        ->each(fn ($child, $k) => $child->update(["property" => $values[$k] ?? null]));
    

    Or, if you're using an unsupported old version of PHP:

    $values = [1, 2, 3, 4];
    $parent->children->each(function ($child, $k) use ($values) {
        $child->update(["property" => $values[$k] ?? null]);
    });