laravel Change Database connection run time

You can change it like this since Laravel 5.x or 6.x

config(['database.default' => 'databasename']);

Where databasename has to be specified in config/database in the connections array.


You can change the connection details during run time using

Config::set('database.connections.mysql.database', 'other_database');

but don't forget to run purge before in order to delete the cache

DB::purge('mysql');

Update: This answer is from 2015! I haven't used Laravel in years and I am not up to date with the latest best practices. This answer keeps getting upvoted so I suppose it works but please proceed with caution.


Well, my immediate answer to this is: don't. Chances are that you can accomplish your task by changing your data model and working with some more advanced relationships. It's hard to tell without knowing what you want to do but it seems to me like a bad idea in general, specially if you're planning on using eloquent models and so on

That said, in some scenario where you really need to alter data in another database or execute some raw query you can use the DB::connection() method. Something like:

$data = DB::connection('another_connection')->select(...);

You can specify that another_connection variable at your database.php file. Like this:

<?php
return array(

'default' => 'mysql',

'connections' => array(

    # Your regular connection
    'mysql' => array(
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'database',
        'username'  => 'user',
        'password'  => 'password'
        'charset'   => 'utf8',

    ),

    # Your new connection
    'another_connection' => array(
        'driver'    => 'mysql',
        'host'      => 'another_host',
        'database'  => 'another_db',
        'username'  => 'user1',
        'password'  => 'password1'
        'charset'   => 'utf8',
    ),
),
);

You can even specify a connection for each eloquent model using protected $connection = 'another_connection'; also you can specify a connection for each model instance created/queried at run time

$user = new User;
$user->setConnection('another_connection');
$user1 = $user->find(1);

But then again, I personally don't think this is a good idea and it seems to me that everything can get messy and fall apart very quickly as your application grows in complexity.

Tags:

Php

Laravel 5