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

borakayalar's avatar

Using Multi Database (one of them defined in .env orher one is dynamic according to client)

I am working on a project in Laravel 10.x. I am trying to use multiple databases (mysql) in my project. The definition for one of these databases is in the .env file. The other database will be determined based on the database ID entered by the user when logging in. However, the other database that has been determined will be the default connection for all models in my project except for the ClientModel. In other words, for all models except ClientModel, the default connection will be database.connections.mysql.database = $ClientSelectedDatabaseId. ClientModel has a predefined constant for this model, and the protected $connection definition uses this connection. My problem is that after the user logs in, all routes under the /admin route will be protected with the auth middleware, and the database.connections.mysql connection will not be purged or reconnected on every page transition or refresh. I use Redis as the session provider. When the session times out, due to the cookie, the user loses the dynamic connection, resulting in a "no selected database" error. What steps should I follow to resolve this error and structure the project correctly?

0 likes
4 replies
Thunderson's avatar

i think you have something wrong in your database conception , why you must have many databases ? if you cannot change, i think you should use two different laravel project for each database and make communication between them by API .

1 like
borakayalar's avatar

@Thunderson Actually there are 2 laravel applications, Main App and Clients App. Main app manage the modules of clients app according to client proffile. Client is the customer who actually purchases the client app. So modules are dynamic any time can remove or install also clients have own user when client buy the app main app creates client database then admin user create for client. The client can connect to own app with admin user then admin will create users into client's database. After that users of client will login with db ID , username and pass.

But I solved the this process. Client app middlewares sequence was wrong :). Right now middlewares handle what I want. Thank you for reply

borakayalar's avatar

@ajithlal thanks for guide, actualy I developt same same way but I saw DB::purge($connectionName) like this. it creates performance problem. I put a middleware it set default connection according to login user session info. Rigth now is so performanced and manageable meanwhile I have to manage all migrations client by client. I writen custom artisan command . Now all things are okay what I want. Also auth system works prefectly :)

Please or to participate in this conversation.