Skip to content
Advertisement

Get specific database connection string while logging and connect to that database dynamically in laravel 8? [closed]

I developed a web accounting application using vanilla PHP as backend and jquery and vanilla javascript as frontend. Every client will have one database. The single database contains all client’s database connection strings and login credentials for clients. Whenever a client logs in using a login credential client gets the connection string from the master database where all database connections are stored. Based on login credentials my backend will connect to their database. They will work on their database.

enter image description here

How can i achieve this scenario using laravel 8? i tried several solutions like, Dynamic database connection in Laravel, Create Dynamic Database Connection in Laravel, Laravel 5.8 dynamic database connection not being set in model, laravel 5.4 dynamic database connection, Configure database connections on the fly in Laravel

these all solutions recommend using configure file or .env file. as you can see in my scenario i can’t setup every client’s database connection in database config array because my client’s database connections are dynamic and there are lots of database connections.

so what you guys will suggest to overcome this scenario?

and i don’t want to use Multi-Tenant setup its just overkill and i do want is grab connection string while logging and use that connection string to connect user’s specific database. so its kind a dynamic!

Advertisement

Answer

  1. Add connection to config/database.php (You may copy and edit the name.) ex. copy and change name to “mysql_user”
  2. Make middleware
  3. Check auth in middleware and get credentials
  4. Set config in middleware
Config::set('database.connections.mysql_user',[
'host' => $user->connaction->host,
'user' => $user->connaction->user,
...
])
  1. When you use
DB::connection('mysql_user')->...

#in Model
protected $connection= 'mysql_user';
  1. Don’t forget to use middleware
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement