Changing The Database Connection For A Route In Laravel
14 Mar 2016
While creating an API in Laravel I had a requirement due to a tight schedule. The content team required a clean database
to start provisioning real data in the backend CMS and the app developer still required the API to serve the full range of
fake seeded data.
We could have created two separate installations of the same Laravel application, but I had a feeling it might be easier to
use two databases (one clean and one seeded) and have them serve the two different route groups “backend” and “api”.
In the generated middleware I use the Config facade to set the ‘database.default’ option to our seeded database connection.
Then I added the middleware to the HTTP Kernal.
And setup the two database connections.
This meant by default any route that didn’t use the ‘seeded.database’ middleware would be using
the default ‘cleanmysql’ connection. And any route using the middleware would have the database connection
overridden to the ‘seededmysql’ connection.
The only thing left to do is apply the middleware to the API routes.