Reputation: 1929
In my project i have to select, on login, which database i want to use in application until next logout.
I'm thinking in way to save de name of database into a global variable but i don't know how.
In this moment i'm trying to set the database on route:
Route::group(['middleware' => 'auth'], function () {
Route::get('app/groups', function()
{
DB::disconnect();
Config::set('database.default','db2');
DB::reconnect();
return view('app.main-folders');
});
});
I do the the login with db1 and the page was returned to app/groups and it is work, change the database to db2 and show the data but when i select another link it seems that it loses the connection because give me an sql error.
Which is the best option to do that? The selection of the database has to be dynamic.
If i save the database name into a global variable i can use that name to do queries:
DB::connection($name)->select(...);
How can i solve that?
Thanks
Upvotes: 0
Views: 1896
Reputation: 5155
Config::set()
will not work in this way. It works per 1 request only. That's why it loses the "new" connection (and keep connecting the original default connection) when you visit to another link.
The only way I think that works is store the new database connection name in session
.
And grab that connection name from session
in your controller constructor.
Example Code:
In your routes;
Route::group(['middleware' => 'auth'], function () {
Route::get('app/groups', function()
{
session(['database_name' => 'db2']);
return view('app.main-folders');
});
});
In your controller;
class ItemController extends Controller
{
public function __construct()
{
// without middleware, you cannot access
// session() in constructor of the controller in Laravel 5.3
$this->middleware(function ($request, $next) {
Config::set('database.default', session('database_name', 'default_database_connection'));
return $next($request);
});
}
public function ListCustomer()
{
$customers = Customer::all();
return $customers;
}
}
Or, if you change connection per Eloquent Model in your controller, you can also try like that;
class ItemController extends Controller
{
public function ListCustomer()
{
$customer = new Customer();
$customer->setConnection(session('database_name', 'default_database_connection'));
$customers = $customer->get();
return $customers;
}
}
But you have to use this approach with extra care. Because it has some caveats when using with relationships.
Upvotes: 1
Reputation: 1
You can find a great solution here: https://laracasts.com/discuss/channels/general-discussion/change-database-name-of-connection-on-the-fly
Upvotes: 0