kevin_marcus
kevin_marcus

Reputation: 277

Laravel 5 Changing Database name in controller

ers. I need to change the database name into a specific controller. I already changed the database.php into this

'sqlsrv' => [
        'driver'   => 'sqlsrv',
        'host'     => env('DB_HOST', 'loal'),
        'database' => env('DB_DATABASE', 'test1'),
        'username' => env('DB_USERNAME', ''),
        'password' => env('DB_PASSWORD', ''),
        'charset'  => 'utf8',
        'prefix'   => '',
    ],
    'sqlsrv2' => [
        'driver'   => 'sqlsrv',
        'host'     => env('DB_HOST', 'local'),
        'database' => env('DB_DATABASE', 'test2'),
        'username' => env('DB_USERNAME', ''),
        'password' => env('DB_PASSWORD', ''),
        'charset'  => 'utf8',
        'prefix'   => '',
    ],

My main DB is test1 and I need to change it into test2 db name in here :

 public function TransactionHistory(Request $request){

    Config::set('database.default','sqlsrv2');

    dd(DB::connection() );
}

But it only returns null and it is still reading test 1. Anyone?

Upvotes: 0

Views: 4327

Answers (2)

Bogdan Koliesnik
Bogdan Koliesnik

Reputation: 900

If you are using Eluquent there is more elegant way Database Connection

  1. Create enother config for second connection

`

   'connections' => array(

    # Our primary database connection
    'mysql' => array(
        'driver'    => 'mysql',
        'host'      => 'host1',
        'database'  => 'database1',
        'username'  => 'user1',
        'password'  => 'pass1'
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),

    # Our secondary database connection
    'mysql2' => array(
        'driver'    => 'mysql',
        'host'      => 'host2',
        'database'  => 'database2',
        'username'  => 'user2',
        'password'  => 'pass2'
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),
);

`

  1. Set connection in your Model:

`

namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
    /**
     * The connection name for the model.
     *
     * @var string
     */
    protected $connection = 'connection-name';
}

Upvotes: 0

jaysingkar
jaysingkar

Reputation: 4435

One way is to change the connection by using DB::connection() method:

$connection = DB::connection('sqlsrv2'); //this will create a database connection using sqlsrv2 in your config.

Now, you can use $connection to run the queries, etc.

Reference :

Upvotes: 3

Related Questions