0

I want to set DB_Database field in .env file according to need at runtime just to switch from one database to other. How to set it from controller ?? is there any way to set .env fields??

4
  • 2
    you can specify database.$users = DB::connection('foo')->select(...); Commented Oct 19, 2016 at 14:28
  • 1
    Provide some code so we can help you! Database choice you setup in model or when you run query DB::connection(connection_name') whereconnection_name is defined in .env Commented Oct 19, 2016 at 14:28
  • This can help you: laracasts.com/discuss/channels/general-discussion/… Commented Oct 19, 2016 at 14:31
  • Thanks to all of you Commented Oct 19, 2016 at 14:42

1 Answer 1

1

Actually it's possible but it is not good idea. For switch between DB you can:

1.Add connection to your config/database.php file:

'connections' => [

    'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

    'mysql2' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

],

2.Specify connection for DB request:

$users = DB::connection('mysql')->select(...);
$users = DB::connection('mysql2')->select(...);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.