I have some code and tried it in two ways. It’s not working as expected and is not rolling back data
Error produce example is in git : https://github.com/Namvarii/laravel-db-transaction-error
DB::beginTransaction();
try {
$order = Order::create([
// data
]);
$order->notes()->create([
// data and cause a fail
]);
// No morph map defined for model [AppModelsOrder].
$order->transaction()->create([
// data
]);
} catch (Exception $e) {
DB::rollBack();
return "error";
}
DB::commit();
return "success";
And
DB::transaction(function() use ($offer, $request) {
$buyer = auth()->user();
$order = Order::create([
// data
]);
$order->notes()->create([
// data
]);
// throw error, "No morph map defined for model [AppModelsOrder]" because not alias is defined.
$order->transaction()->create([
// data
]);
});
return "success";
In the two of them, a morph alias error occurs and the request fails with the message No morph map defined for model [AppModelsOrder]
, but I wonder why Order::create([/* data */]);
is not rolled back and is stored in the database.
2
Answers
you commit transaction after try cache,
Whether you are has error or not, transaction commit,
change code like this :
When you create a model and its relationships within a transaction, if an exception occurs, Laravel will automatically roll back the entire transaction, undoing any changes made within that transaction.
However, in your case, the issue is related to the fact that Laravel is trying to perform the rollback, but the morphMap is not yet defined, leading to the "No morph map defined for model [AppModelsOrder]" error. This error prevents the transaction from rolling back successfully.
To address this issue, you should define your morph map before creating any models or relationships that involve polymorphic relationships. You can define the morph map in the boot method of your AppServiceProvider or any other service provider. Here’s an example:
Now, Laravel will know how to resolve the morph aliases even during a rollback within a transaction.