Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

asufayran's avatar

SAAS multiple databases

Hey guys, I have a SAAS laravel application, and it's working fine using single database, but many clients approached me about offering multiple databases option, where they can bring their own database. I read the docs and I know it can be done, I just have trouble wrapping my head around first time installation. Like from the moment the user signs up and how to run migrations on their server etc. Anyone been through something similar?

0 likes
4 replies
bobbybouwmann's avatar

You can use a middleware to set the correct config for the database. This way, you can swap the database connection whenever needed. You can then store the correct credentials in the config or in some default database.

Something like this should work:

public function handle($request, Closure $next)
{
    $credentials = $this->getCredentialsFromCurrentUser($request->user);

    Config::set('database.connections.mysql.database', $credentials['database']);
    Config::set('database.connections.mysql.username', $credentials['username']);
    Config::set('database.connections.mysql.password', $credentials['password']);

    return $next;
}
asufayran's avatar

@bobbybouwmann sure, but how will I initialize the remote database in the first place. In typical SAAS application with multiple databases, after the user signs up, you create a database for them, run migrations, and then use the config to specify the connection. All of that happens on the same server. But in my case, clients want to host their own database, and let me keep the code. How will run migrations remotely in this case?

bobbybouwmann's avatar

You can set the host of the database right? If you use their database credentials and their URL it should work the same as connecting to your own database.

asufayran's avatar

Then just run migrations using php artisan migrate?

Please or to participate in this conversation.