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', 'info.country', 'images', 'packages.package.info.country')->firstOrFail()

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

Products::where('id', $id)->with('category', 'info.country', 'images', 'packages.package.info.country')->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.

    DB::beginTransaction();
    
    try {
        $product = Product::find($id);
        $product->category()->update([
            'name' => 'Category 1',
        ]);
        // rest of the statements
    
        DB::commit();
        // all good
    } catch (\Exception $e) {
        DB::rollback();
        // something went wrong
    }