How to use non-default DB connection with eloquent in Laravel

Categorized as Laravel Tagged

When you use the Laravel eloquent models on a non-default database connection, the default database transaction will not work. You have to specify the DB connection type before opening the transaction.

// Update users and posts
DB::connection('mysql_2')->transaction(function () {

  \App\Models\User::query()->update([...]);

  \App\Models\Post::query()->update([...]);

}, 5);

Leave a reply

Your email address will not be published. Required fields are marked *