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

halo509's avatar

Same laravel site, but different databases and logins

I need the simplest way of how I would have one installation of laravel, serving a site. But depending on the url, I can access different databases. for example:

www.domainname.com/company1/login - database1 www.domainname.com/company2/login - database2

So, the site being served is the exact same site. But, each part has its own login, and accesses a different database.

I know I can do this by having multiple installations of laravel, and that how I am doing it right now. but I wanna be able to just update ONE version

Thanks

0 likes
14 replies
halo509's avatar

thanks for ur replay but actually they are more than two, i just wrote that for example, and the databases are huge

halo509's avatar

look, it will be the same system for many companies, so i need each company in a separate database

all database will be have the same structure but different data, i know that i can make all in one database with an identifier for each company, but i need to make them separated

Snapey's avatar

look, there are two ways of running multi-tenancy, 1 - shared database, 2 - database per client

You are talking about the database per client approach. So look for multi-tenancy tutorials and all will become clear

1 like
halo509's avatar

i think it's a good way, but i can not find a mutli-database package for laravel 5, can u help me in this?

slev1n's avatar

@halo509 as possible solution:

You can make global http middleware, that will configure default db connection, based on required logic.

Describe your connections in config/database.php and add your middleware to app/Http/Kernel.php:

// app/Http/Middleware/ConfigureCompanyDatabase.php
public function handle($request, Closure $next)
{
    $company = request()->segment(1) ?? 'default'; // will return your route company segment
    $connection = $this->getConnectionForCompany($company);

    config()->set('database.default', $connection); // swap default database connection
    DB::purge(); // purge existing connection, db will reconnect with provided credentials on first db request.

    return $next($request);
}

protected function getConnectionForCompany(string $company): string
{
    // make it as const array or load from your own configuration file, etc.
    $connections = [
        'company1' => 'database1', // see config/database.php => connections array
        'company2' => 'database2',
    ];

    return $connections[$company] ?? 'default';
}
halo509's avatar

@slev1n thanks for ur reply, but i need to know how the file structure and requests urls will be in this case?

i added the database and make the middleware

but i can not figure out how the URLs should be, it always getting error

slev1n's avatar
// web.php or api.php
Route::prefix('{company}')->group(function () {
	// Route::get, Route::post, etc
});

// and your request will be domain.tld/company1/some_route
// or domain.tld/api/company1/some_route (in case of api request change request()->segment(1) 1 to 2 )
slev1n's avatar
slev1n
Best Answer
Level 4

simple fast full working example:

// config/companies.php
return [
    'company1' => 'company1',
    'company2' => 'company2',
    'default' => 'mysql',
];

// config/database.php
// defaut for mysql + 

'company1' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE_1', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
        ],
'company2' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE_2', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
        ],

// .env
DB_DATABASE=some_db_name
DB_DATABASE_1=some_db1_name
DB_DATABASE_2=some_db2_name


// middleware.php

public function handle($request, \Closure $next)
    {
        $company = request()->segment(2) ?? 'default';
        $connection = $this->getConnectionForCompany($company);

        config()->set('database.default', $connection);
        DB::purge();

        return $next($request);
    }

    protected function getConnectionForCompany(string $company)
    {
        if (! $connection = config("companies.$company")) {
            $connection = config("companies.default");
        }

        return $connection;
    }

// Kernel.php

protected $middleware = [
	...
        SomeMiddleware::class,
    ];

// api.php
Route::prefix('{company}')->group(function () {
    Route::get('/test', function () {
        return \App\Models\User::latest()->first(); // different results for /api/company1/test, /api/company2/test, etc
    });
});

1 like
halo509's avatar

here's what i did, but after redirect database is retested to the default connection , isn't the database change will be globally?

'company1' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE_1', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
        ],
'company2' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE_2', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
        ],

// .env
DB_DATABASE=some_db_name
DB_DATABASE_1=some_db1_name
DB_DATABASE_2=some_db2_name


// middleware.php

public function handle($request, \Closure $next)
    {
        $company = request()->segment(2) ?? 'default';
        $connection = $this->getConnectionForCompany($company);

        config()->set('database.default', $connection);
        DB::purge();

        return $next($request);
    }

    protected function getConnectionForCompany(string $company)
    {
        if (! $connection = config("companies.$company")) {
            $connection = config("companies.default");
        }

        return $connection;
    }

// Kernel.php

protected $routeMiddleware= [
	
        'configureCompanyDatabase' => \App\Http\Middleware\configureCompanyDatabase::class,
    ];

// web.php
 Route::get('/{company}/login', function () {
  return redirect()->route('login');
})->middleware('configureCompanyDatabase');
slev1n's avatar

globally for current request. Each your request has to be with company name in route, if you haven't any other type to determine which database must be used now (some token in cookie, some authenticated user model variable, etc).

Check link that @snapey leaved, may be that package will solve your problem?

1 like

Please or to participate in this conversation.