How to Route Model Bind with dynamic database connection?

Hi good people. Have been stuck for hours on end with model binding with dynamic DB connection. I have a multi-tier system, more like SAS app, where users can log into different databases depending on the organization. I have managed to do this with the middleware, where it picks the user's ID and is able to refresh connection by pointing to another database. Generally it is done with the following code;

\Config::set('database.connections.orgdb.database', \Auth::user()->db);

Now when I set up route binding in the RouteServiceProvider, am unable to access the Auth::user() It is returning null. Apparently it is loaded after routes are bound. Is there a way to ensure Routes are bound after Auth has been loaded?


Xtreem Developer replied 1 year ago

If you just want a different connection for a specific model, set it's protected $connection variable in the model class to the name of the connection you want it to use.

By:Xtreem Solution

Highly Skilled Laravel Developer

Dedicated PHP Developer

angujo replied 1 year ago

Thanks @xtreem But that is not what am looking for. I need to switch the database from within a given connection on the fly. Setting $connection in the model has been done, now the issue is changing the database in that connection for route model binding.

I hope it is clear.

Zuhaib Arshad replied 1 year ago

@angujo did you able to find out the solution for this ?

Sign in to participate in this thread!

We'd like to thank these amazing companies for supporting us