How to save tables with relationship in Laravel?

0

I'll give you a small example to explain my problem.

Tables:

main
itens

The two have a relationship, a main has several itens .

What I'm doing to save:

...
$main = $this->main->create($postCreate);
foreach ($postCreate['itens'] as $item){
    $item['main_id'] = $main->id;
    $this->itens->create($item);
}
...

It works, but if there is an error when saving the items, it is to save the main without the items or missing some items, I wanted to save everything, and if there were any errors do not save anything.

How to save tables with relationship in Laravel?

    
asked by anonymous 27.04.2018 / 22:13

1 answer

0

I have decided as follows

I imported the following class:

use Illuminate\Support\Facades\DB;

And I put my code inside transaction :

return DB::transaction(function () use ($campos){
    return $this->meuMetodo($campos);
});

In this way, all transactions that are within meuMetodo will only be actually saved if all transactions are true.

    
27.04.2018 / 23:12