How to make database transaction with Laravel

This is another important feature that is missing from the docs(at least at this moment), but you can find it on API docs.  I’ve found that there are 2 ways:

With PDO:

DB::connection()->pdo->beginTransaction();

DB::connection()->pdo->commit();

DB::connection()->pdo->rollBack();

More info about it here

Or with DB object:

DB::transaction(function() use ($user_id)
{
    DB::table('user')->delete($user_id);
    DB::table('user_permissions')->where('user_id', '=', $user_id)->delete();
});

DB::transcation() uses PDO to perform the transaction.

Advertisements

One thought on “How to make database transaction with Laravel

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s