Laravel + DB Transactions + Multiple Connections

Feels like I’ve got more to talk about work than running lately. ^^;

At work, I’ve got two applications that has multiple database connections for security reasons. I’ve been running into a weird issue with Laravel and transactions and rollbacks not firing on the secondary database. I thought it was something I did, but it’s actually Laravel.

So in the application, I’ve got an Eloquent model that is using the secondary database connection. I’ve got a save functionality to create a new user (for example) with multiple relationships. However, the rollback wasn’t firing when a relationship failed to save properly and the try/catch was firing. Well I just figured out why. I wasn’t telling the transaction to use the secondary database. It was creating a transaction for the primary database. Here’s how to do it:

<?php DB::connection('name_of_your_secondary_connection')->beginTransaction();  ?>

You’ve gotta add the connection() to each rollback and commit as well.

There’s your tip of the day! 🙂