LorenzoBerti
LorenzoBerti

Reputation: 6974

Laravel 5 - save models in db sequentially

So I'm here to ask you a logic question.

So I have a Car model with These properties: id, name, description.

Then I have a second model named CarOptional which is actually a relationship model with the third Optional model and it has these properties: id_optional, id_car.

Then I have a third model that is CarColours (which we pretend is a similar table to carOptional) with id_colour, id_car properties.

Now I'm going to save a new Car, so I'll go with the method $car = Car :: create (arraydatas).

Saved my data on db i have my car model so i can have her id and rescue CarOptional es.

ForEach ($ optionals as $ optional) {
   CarOptional :: create (array ("id_car" => $ car-> id, "id_optional" => $ optional-> id))
}

So, I do same with the CarColours model, so the cycle with the create method, but what I ask is:

How do I handle the creation error (for example) of CarOptional, and then stop all subsequent created and do I want to "remove" on the db the previously saved, and returning an error?

Upvotes: 1

Views: 213

Answers (1)

Chemaclass
Chemaclass

Reputation: 2011

What you are asking for is called: Transactions

<?php
namespace ProjectName\Whatever\Mappers;

final class CarMapper {

    public function createCar($car, $optionals, $colors) {
        DB::transaction(function () use($car, $optionals, $colors) {
            $this->createOptionals($car, $optionals);
            $this->createColors($car, $colors);
        });
    }

    private function createOptionals($car,$optionals) {
            foreach($optionals as $optional) {
                CarOptional::create([
                    'id_car' => $car->id,
                    'id_optional' => $optional->id
                ]);
            }
    }

    private function createColors($car,$optionals) {
        foreach($colors as $color) {
            CarColour::create([
                'id_car' => $car->id,
                'id_colors' => $color->id
            ]);
        }

    }
}

In simple words: with a SQL Transaction, if something goes wrong in the middle of the transaction nothing will be commited. You won't need to care about "and then stop all subsequent created and do I want to 'remove' on the db the previously saved".

This is the part where you should focus:

DB::transaction(function () {
    // ... 
});

Upvotes: 1

Related Questions