Answer the question
In order to leave comments, you need to log in
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,
]);
Answer the question
In order to leave comments, you need to log in
those. in transaction it is possible to wrap NOT ONLY methods of facade DB?
DB::transaction(function () {
$post = Post::create();
$comment = $post->comments()->create([
'message' => $request->message,
]);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question