R
R
Romi2021-12-14 15:31:10
Laravel
Romi, 2021-12-14 15:31:10

Is it possible in Eloquent to make the creation of two dependent (hasOne) models as a transaction?

The Laravel documentation discusses either transactions using the DB facade or saving related models (via save() or push() ) using an already existing model with respect to hasOne.

But what if you want to create EITHER two related models OR none?

Those. let's say we created the Main model, and when we created the child Props model, something went wrong, and now we need to delete Main, because we don't need it without Props.

Are there any out-of-the-box methods in Laravel to handle this kind of situation?

Thank you.

upd.: an example for clarity (I will slightly change the example from the docks)

use App\Models\Post;

$post = Post::create();

$comment = $post->comments()->create([
    'message' => $request->message,
]);


Let's say you need not just $post, but exactly $post with this comment, and without a comment, the post is not needed at all. And at the moment of creating $post->comments()->create(), something went wrong - either the data in the request was not the same, or something else, in general, an exception - but $post has already been created - and he without comment - is NOT needed. Here is such a situation.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Romi, 2021-12-14
@romicohen

those. in transaction it is possible to wrap NOT ONLY methods of facade DB?

answer from Alexey Ukolov
Naturally. Eloquent not through magic of a line inserts into tables.
***
It looks like this:
DB::transaction(function () {

$post = Post::create();

$comment = $post->comments()->create([
    'message' => $request->message,
]);

});

should work too :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question