LARAVEL - Multiple databases per user, user choses database connection each time

Viewed 2604

fairly new to Laravel so accept my apologies in advance if I am lacking any essential knowledge.

So, I am building an app where each user can login to a personal dashboard. This dashboard displays data from a certain database. Each user has multiple databases but each database belongs to only one user. The user can create new databases from the dashboard (this is handled by the back-end, only mentioning it to give you a better idea of how the app works). Finally, there is a separate database, common for all users where the user-database relationships are stored.

What I need for every user is:

When they log in, their dashboard displays data of the latest created database that belongs to that user. The user can then select what database they want to "view" from a dropdown menu and dashboard contents change accordingly. Now, I have this working for a single database per user (hard-coded) but want to add the dynamic element described above.

I found something similar here:

https://laracasts.com/discuss/channels/general-discussion/change-database-name-of-connection-on-the-fly?page=1

but there seem to be some answers missing from the thread so could not quite follow it.

Each one of the databases has the exact same structure so there is only one controller and model needed that will dynamically get values for database name.

So the workflow what I would need looks as follows:

  • User logs in
  • View composer gets a list of all available databases for that user and generates a dropdown menu
  • Model connects to latest created database
  • Controller uses that connection to retrieve and pass data to the view
  • User selects a different database from the dropdown menu
  • Model connection updated to new selected database
  • Controller uses that connection to get data from that database to pass to view

My main issue is defining the procedures that will assign a the current database name to a variable and then the models use this variable to set up a dynamic connection and finally call controllers to retrieve and show data.

Is a process like that feasible and what would be the best approach towards it?

Thank you in advance for the help!!

1 Answers
Related