I have a initial page which has a drop down of 5 options, The 5 options are 5 different databases, The functionality that I need to achieve is the same for all databases.
The thing I want to do if I select Option A, it should connect to Database A and give me results on View A.
If I select Option B, it should connect to Database B and still give me results on View A.
I don’t want to make multiple views for the same thing.
Is there any way the above functionality could be achieved?
Thanks
3
Answers
do you have multiple connections for different database in
config/database.php
?. If not, you could create multiple connections asdatabase_a
anddatabase_b
. If you already have multiple connections for different database, you could make different connection depending on the requests you get.link : https://laravel.com/docs/11.x/database section #Using Multiple Database Connections
Hope it helps you! Tell me if it’s not working.
You could just change your database query’s connection depending on the value sent as the selected option
Or alternatively your db connection could be part or the url.
If you only need to use one database at a time, you can simply modify the basic MySQL connection, but you can also declare new connections as needed in the
config/database.php
file.Let’s assume that the database selection occurs at the /login URL, and the database usage takes place on all routes starting with /admin. You can declare a middleware that will be associated with every route starting with /admin, and for such a route, it will set the name of the selected database.
At the /login URL, you can save the name of the selected database into a session variable. Afterward, you redirect the user to an /admin/tables or some kind of homepage, where the middleware is triggered. The middleware then utilizes the session variable, retrieves the requested database name, and sets it in the connection as follows.
So, on every /admin route where the
DatabaseSelector
runs, you can useDB::connection('another_name')
for querying. You can associate Eloquent Models with it by setting the $connection value toanother_name
in the Model file, etc.The connection named
another_name
will always connect to the database with the selected name. On the /login page, its only job is to precisely write the name of the database to theselectedDatabase
session variable, selecting one from the 5 databases available.Of course, I tried to demonstrate the logic. Try to interpret and consider what logic you would need. The key is that you can declare connections, and you can modify their data at runtime based on the description. I provided you with an example where you can select the database at the /login URL, and the middleware invoked at the /admin URL automatically checks and sets it in the config.