Abishek
Abishek

Reputation: 11691

Transactions and Events in Laravel 4

When an Event is fired from within the Laravel's closure transaction function, are the Database operations within the Events also part of the Transaction or are they outside of it?

Snippet 1
    Event::listen('fireme',function($data){
         User::where('votes', '>', 100)->update(array('status' => 2));
    });

Snippet 2
    DB::transaction(function(){
            User::where('votes', '>', 100)->update(array('email' => '[email protected]'));
            Event::fire('fireme',array('email' => '[email protected]'));
    });

Does Snippet 1 belong to the transaction defined on Snippet 2?

Upvotes: 3

Views: 1396

Answers (2)

Jason
Jason

Reputation: 4772

If you only have one database connection, and you are within a transaction, then everything you do in the database must be a part of that transaction. Laravel does not open additional database connections for events.

Upvotes: 1

casafred
casafred

Reputation: 666

I had exactly the same question.

Following the suggestion of @alexandre-danault, I can confirm that exceptions thrown within an event handler, where the event is fired from within a transaction, will cause the transaction to rollback. I figured putting this answer up might save you having to run your own test first. Here are my code snippets (I'm not using the closure form of transactions):

// I throw an exception from within this event handler
Event::listen('transaction.statusChange', 'TransactionHandler@onStatusChange');

// Here's the transaction that fires the event
DB::beginTransaction();
try {
    $this->status = $status;
    if (!$this->save()){
        throw new Exception('...');
    }
    Event::fire('transaction.statusChange', ['transaction' => $this, 'status' => $status]);
} catch(Exception $e){
    DB::rollback();
    // Log exception

    return false;
}
DB::commit();

Upvotes: 1

Related Questions