Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

How to change the default DB connection for a specific controller?

Hello,

Is it possible to set/change the default DB connection on a specific controller to avoid writing DB::connection every time? This controller needs only this connection

thanks

0 likes
5 replies
gych's avatar

You could use middleware for this, group all routes for the default DB connection in a middleware 'defaultDBConnection' or 'DBConnection1' for example and create a separate middleware for the routes that use the specific controller.

Then in those middleware's set the desired DB connection.

Ligonsker's avatar

Thank you, how can I set the specific connection in this middleware?

gych's avatar

@Ligonsker

You can either change the database connection from the config

use Illuminate\Support\Facades\Config;

$connection= config('database.connections.yourconnection');
Config::set('database.connections.mysql', $connection);
DB::purge();

or use DB facade to set the connection

use Illuminate\Support\Facades\DB;
DB::setDefaultConnection('yourDBConnection');
1 like
gych's avatar

I've updated/improved my example in my last reply

Please or to participate in this conversation.