Laravel updating multiple related models

I'm trying to update multiple models at once, I didn't tried any function so far, but I would not if there is no way of doing it. For example, I have model Products and there is few relations, with another relations inside. And I'm getting it like this:

Products::where('id', $id)->with('category', '', 'images', '')->firstOrFail()

So is there any way to make update function at once? For example

Products::where('id', $id)->with('category', '', 'images', '')->firstOrCreate($request);

Is that possible?

1 answer

  • answered 2021-04-21 14:32 P. K. Tharindu

    You can't update multiple models with a single statement as you can't update multiple tables in one SQL statement. However, you can use a transaction to make sure that all statements are treated atomically.

    try {
        $product = Product::find($id);
            'name' => 'Category 1',
        // rest of the statements
        // all good
    } catch (\Exception $e) {
        // something went wrong