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

Grunk's avatar
Level 1

Choose database at login

Hi, i'm fairly new to laravel but not at all with php. I'm used to handling everything , and now i'm kind of lost with laravel doing all the work for me :D

I set up an authentification. On the login view i added a select which allows me to choose which database to query. (basically i have a db per corporation using the tool).

What i want to do , is ,setting the database to use, dynamically, at login. So user fill the form , clic the 'login' button and before anything i should define the database to use according to what is selected in the login form.

From what i understand this is possible by using something like : Config::set('database.connections.mysql.database', 'DB_SELECTED_AT_LOGIN');

1- Is this correct ?

2- If so, is it mandatory to completly rewrite the LoginController and redefining routes as explained here : https://laravel.com/docs/6.x/authentication#authenticating-users ? i don't see any other option to get the additional parameter from the login form

3- once i manage to get the parameter containing the db name how do i persist this setting during the user session ? The middleware solution given by @fylzero in this thread : https://laracasts.com/discuss/channels/laravel/laravel-dynamic-database-connections seems to be a good solution but , in my case i'm before the authentification process.

Thanks for your help

0 likes
7 replies
Grunk's avatar
Level 1

Thanks, but my problem is not to work with multiple database at the same time , but choose one among many at runtime and more precisely at login

flightsimmer668's avatar

From what i understand this is possible by using something like : Config::set('database.connections.mysql.database', 'DB_SELECTED_AT_LOGIN'); 1- Is this correct ?

It should work, provided a database with a matching name actually exists on the server. I think you could set this in the controller login method after you've authenticated the user.

2- If so, is it mandatory to completely rewrite the LoginController

You won't need to completely rewrite the default Laravel LoginController for this; you can just modify it to accept a database_name variable. Which leads to another question -- are you going to be hard-coding the list of database options in your login form OR is it going to be a list generated by the application? If it's the latter, then I think you have some decisions to make about where that data is going to come from and you may need another route + controller method to fetch that list of databases, or the login view needs to be passed that list of databases.

3- once i manage to get the parameter containing the db name how do i persist this setting during the user session ?

The middleware solution you mentioned could work for this, but I get that you need a reference to which database was selected. Perhaps using session variables in combination with middleware could work for you... https://laravel.com/docs/6.x/session#storing-data

My answers are based on the limited information about the structure of your application. If I had more details, I may be able to help in more detail.

Have a nice day

Sti3bas's avatar
Sti3bas
Best Answer
Level 53

@grunk what about:

View (add new field):

<div class="form-group row">
    <label for="database" class="col-md-4 col-form-label text-md-right">{{ __('Database') }}</label>

    <div class="col-md-6">
        <select name="database" class="form-control @error('database') is-invalid @enderror" required>
            <option {{ old('database') === 'db1' ? 'selected' : '' }} value="db1">DB1</option>
            <option {{ old('database') ===  'db2' ? 'selected' : '' }} value="db2">DB2</option>
        </select>

        @error('database')
            <span class="invalid-feedback" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>

LoginController:

class LoginController extends Controller
{
    use AuthenticatesUsers {
        attemptLogin as baseAttemptLogin;
    }

    protected $redirectTo = RouteServiceProvider::HOME;

  
    protected function attemptLogin(Request $request)
    {
        config(['database.connections.mysql.database' => $request->database]);
        
        return $this->baseAttemptLogin($request);
    }

    protected function authenticated(Request $request, $user)
    {
        session(['database' => $request->database]);
    }

   protected function validateLogin(Request $request)
   {
      $request->validate([
         'database' => [
            'required',
            Rule::in(['db1', 'db2']),
         ],
         $this->username() => 'required|string',
         'password' => 'required|string',
      ]);
   }
}

app\Http\Kernel.php:

protected $middlewareGroups = [
    'web' => [
       //...
        \Illuminate\Session\Middleware\StartSession::class,
        \App\Http\Middleware\SetDBConnection::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        //...
    ],

    /...
];

app/Http/Middleware/SetDBConnection.php:

namespace App\Http\Middleware;

use Closure;

class SetDBConnection
{
    public function handle($request, Closure $next)
    {
        if (session('database')) {
            config(['database.connections.mysql.database' => session('database')]);
        }

        return $next($request);
    }
}
1 like
Grunk's avatar
Level 1

Thanks guys for your answers. @sti3bas i'll try this tomorrow. it's how i imagined it but didn't know how to implement it the laravel way. Thanks

jlindsey's avatar

Seems like this has already been answered but I just want to confirm that yes you can indeed set up and/or reconfigure connections at runtime. In my own project I did it like this:

$dynamicConnection = [ 'driver' => 'mysql', 'host' => '127.0.0.1', ...]
config(['database.connections.dynamic' => $dynamicConnection]);
DB::purge('dynamic');

Just a few things I discovered:

DB::purge is important.

You can use middleware to inject the connection info at runtime, which is what I did. You could also potentially do it in a service provider.

Check out config/database.php to see what connection is default. If you update the default connection, everything will just work. But if your dynamic connection is not default, you will have to manually reference it in your models and queries.

For models, just add protected $connection = 'dynamic'

For queries, use DB::connection('dynamic')->select(...)

Good luck!

Grunk's avatar
Level 1

i just tested @sti3bas solution and it's working perfectly. Thank you very much. I just need to apply some modification to the password restoration process to handle the correct database and i'm good to go.

1 like

Please or to participate in this conversation.