change database connection just for 1 user

834 views Asked by At

I need to use another db connection just for 1 user.

First of all I created another connection in the config/database.php file:

'mysqltest' => [
    'driver' => 'mysql',
    //...
],

It works. I tried it with something like this Model::on('mysqltest')->all().
Now I would like to change connection everywhere in the project, so I thought to change it after user login.
I'm trying this without success:

protected function authenticated(Request $request, $user)
{
    //
    if ($user->user_id == 1) {
        //DB::purge('mysqltest');
        //DB::reconnect('mysqltest');
        DB::setDefaultConnection('mysqltest');
    }
}
1

There are 1 answers

2
Yauhen Kib On

Create middleware for example

php artisan make:middleware SelectDB

    <?php

    namespace App\Http\Middleware;

    use Closure;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\DB;

    class SelectDB
    {

        public function handle(Request $request, Closure $next)
        {
            if (auth()->id() == 1) {
                DB::setDefaultConnection('mysqltest');
            }

            return $next($request);
        }
    }

Add middleware in App\Http\Kernel

    protected $middlewareGroups = [
            'web' => [
                \App\Http\Middleware\SelectDB::class,
                \App\Http\Middleware\EncryptCookies::class,
             ...