I want to insert two rows into two different tables simultaneously. for that, I have used Laravel created event in my first model to create the other one but I'm not sure if Laravel use database transaction to roll back if anything goes wrong. Does Laravel use database transaction in events?
here is my code:
class MyFirstModel extends Model {
/* My Event
___________________*/
protected static function boot()
{
parent::boot();
static::created(function ($myFirstModel) {
MySecondModel::create([
'someData' => $someData
]);
});
}
CodePudding user response:
In the documentation there is a part how to use database transactions.
https://laravel.com/docs/9.x/database#database-transactions
use Illuminate\Support\Facades\DB;
DB::transaction(function () {
DB::update('update users set votes = 1');
DB::delete('delete from posts');
});
you can wrap it with the transaction function. I think by default there is no transaction used.
CodePudding user response:
If the code who triggered the event is inside a transaction, the event will be under the same transaction.
DB::transaction(function () {
(new Model)->create([]);
// ^ This triggers the `creating` and `created` event on the same transaction.
})