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

leinad95's avatar

How to change database for specific model

Hello! I have an issue with a project I'm working on now and I need some help. I build an admin panel in laravel and for that I have a MySQL db setup and working. Now, I need for a specific model (but only when I config this) to use a different database. The problem is that I cannot set this up in config/database.php as a new connection because the database name is stored in my admin panel main database, in a table. How can I take that database name from my main admin's db and use the same credentials to make a model work with that specific database, but not interfering with the current db of the admin panel?

Thank You very much!

0 likes
3 replies
leinad95's avatar

Thank you for the answer but I was looking for a way to define the database on the fly. The database name in in my admin panel main db . I cannot set this up front in the config/database.php file

willvincent's avatar

You should be able to dynamically create a new connection in code, when needed.. then use that connection.

Probably you'd want some kind of middleware that checks the appropriate table with that config, and if whatever criteria matches, create the new connection, and maybe set a variable in the session with the connection name to be used, then in the model set the model's connection based on that session variable.

Please or to participate in this conversation.