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');
}
}
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,
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With