Kanu
Kanu

Reputation: 57

Two database connect in laravel

How to connect two database in laravel-5 and how to get data from db.

I know two one thing for that

In config/database set like this.

    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'larashop'),
        'username'  => env('DB_USERNAME', 'root'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

 'mysql2' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST', 'localhost'),
            'database'  => env('DB_DATABASE', 'larashop2'),
            'username'  => env('DB_USERNAME', 'root'),
            'password'  => env('DB_PASSWORD', ''),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],

Upvotes: 0

Views: 849

Answers (2)

Kanu
Kanu

Reputation: 57

I have find the issue of connect 2 database in laravel.

If any body wants two work with 2 database then config as par above suggestion and remove database configuration from .env file which is located at root.

I have tried and I am working with 2 database.

Upvotes: 1

user5633496
user5633496

Reputation:

Using Query you can define a connection on the Query Builder:

$users = DB::connection('mysql2')->select('your query');

Using Eloquent You can also define which connection to use in your Eloquent models as well!

<?php

class SomeModel extends Eloquent {

    protected $connection = 'mysql2';

}

You can also define the connection at runtime via the setConnection method.

<?php

class SomeController extends BaseController {

    public function someMethod()
    {
        $someModel = new SomeModel;

        $someModel->setConnection('mysql2');

        $something = $someModel->find(1);

        return $something;
    }

}

Upvotes: 1

Related Questions