Anyone? Help?
[L5] Change Default Database connection Dynamically.
I want to set the default database connection dynamically.
Config::Set() will do it for 1 request only. I want it for every subsequent request.
I can do it by storing it in session, and do the Config::set() for every request. But that is not the efficient way for my application.
I have a logic but i dont know how to implement it.
Logic is to set the environment variable dynamically. But i don't know how to do it?
What will trigger a db change?
I have set of organizations as client. And each client have a separate database. so after logging in, I will change the db according to the client (Organization)
You can do something like this in your model, as an example
class SomeModel extends Eloquent {
protected $connection = 'mysql2';
}
Check out this blog post: http://fideloper.com/laravel-multiple-database-connections
@blackbird Ya I know about this, But I have same model for all organizations, so i will be using same model everywhere. So this will not meet the needs of me.
And yea, setting Environment variable will also not help.
So Far The Best solution is to change the default database connection for every request.
@SachinAgarwal Check out this thread, i had the same problem and solved it! :D.
@uxweb I saw that, But I did not truly understand the solution. Can you please elaborate?
@SachinAgarwal Yep, also i have created a demo with a fresh install of Laravel 5.
Here is the repo!:
https://github.com/uxweb/laravel-multi-db
Check it out and tell me what you think!.
I have a system where I need to change my connection dynamically in my main database I have a table with the parameters for other databases (some times in other servers) Then I do
$nameKey = 'NameOfConnection';
$dataSync = AtlasBases::find($id_client);
Config::set('database.connections.' . $nameKey, array(
'driver' => 'mysql',
'host' => $dataSync->site_db_server,
'database' => $dataSync->site_db_base,
'username' => $dataSync->site_db_user,
'password' => $dataSync->site_db_password,
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
'prefix' => '',
));
# And set the new connection to my models
$imobModel = new ImobImoveis;
$imobModel->setConnection($nameKey);
Very simple, but works nice to me
Hope I can help you
@marlon in which file you did this code?
@uxweb I did it with similar logic, But i did not create a package for api, i just retrieve my databases name from a table, and set the name of the database for the connection. Your solution helped me making this logic, thanks :D
@Marlon Ya I figured it out yesterday, I made something similar. :)
Hello Sachin, do you mind sharing your solution ? I am stuck on the same problem, and \Config::set() is not taking me anywhere; only for that one request.
Set database connections in your config/database.php :
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST'),
'port' => env('DB_PORT'),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
'mysql2' => [
'driver' => 'mysql',
'host' => env('DB_HOST'),
'port' => env('DB_PORT'),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
],
Create middleware setDB:
namespace App\Http\Middleware;
use Cookie;
use Config;
use Closure;
use DB;
use App\User;
use Auth;
use Session;
class SetDB
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if($request->has('auth_token') || Session::has('auth_token')){
if($request->has('auth_token')){
$token=$request->get('auth_token');
$result=DB::connection('mysql2')->table('mst_editor_database_info')->where("auth_token",$token)->first();
DB::disconnect(env('DB_DATABASE'));
if($result == null ) {
Auth::logout();
Session::flush();
return redirect('/');
//return redirect('http://www.webtart.com');
}else{
if($result->is_first==1){
DB::connection('mysql2')->table('mst_editor_database_info')->where("id",$result->id)->update(array("is_first"=>0));
DB::disconnect(env('DB_DATABASE'));
$user=User::findorfail(1);
Auth::login($user);
Session::put('auth_token',$token);
Session::put('DB_DATABASE',$result->dbname);
Session::put('site',$result->paths);
return redirect('/info');
}
$user=User::findorfail(1);
Auth::login($user);
Session::put('auth_token',$token);
Session::put('DB_DATABASE',$result->dbname);
Session::put('site',$result->paths);
return redirect('/');
}
}
if(Session::has('DB_DATABASE')) {
Config::set('database.connections.mysql', array(
'driver' => 'mysql',
'host' => env('DB_HOST'),
'port' => env('DB_PORT'),
'database' =>Session::get('DB_DATABASE'),
'username' => 'username',
'password' => 'password,
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
));
DB::reconnect('mysql');
}else{
Auth::logout();
Session::flush();
return redirect('/');
}
}
return $next($request);
}
}
Register middleware in your App\Http\Kernel.php:
'web' => [
\App\Http\Middleware\SetDB::class,
],
Using middleware in your routes.php :
Route::group([
'middleware' => 'web'
], function (){
});
@uxweb how can I contact you in private?
- Click on his account
- Click on twitter/Github icon
I created two connections in database config:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'database_name'),
'username' => env('DB_USERNAME', 'localhost_admin'),
'password' => env('DB_PASSWORD', '******'),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
'mysql_admin' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => 'database_name1',
'username' => env('DB_USERNAME', 'localhost_admin'),
'password' => env('DB_PASSWORD', '*******'),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
and then I just call this function
DB::setDefaultConnection('mysql_admin');
@sachinagarwal would you like to share your solution i am also working on multiple database connection we have client wise database.?
Please or to participate in this conversation.