Laravel DB facade to use several DB

2k views Asked by At

Below is how to use Facade for search table data with pagination in Laravel.

DB::table('customers')->paginate(15);

but it can be use just a DB,

So how to use several DB in Facade sentence?

I wish to use DB as divide as read and write DB or direct access in single sentence.

Thank you in advenced.

1

There are 1 answers

0
Alex Slipknot On BEST ANSWER

First of all you have to specify configuration for your databases in .env:

DB_CONNECTION=mysql
DB_HOST=172.17.0.1
DB_DATABASE=my_database
DB_USERNAME=username
DB_PASSWORD=password

DB_SLAVE_HOST=172.17.0.1
DB_SLAVE_DATABASE=my_database_slave
DB_SLAVE_USERNAME=username2
DB_SLAVE_PASSWORD=password2

DB_MASTER_HOST=172.17.0.1
DB_MASTER_DATABASE=my_database
DB_MASTER_USERNAME=username
DB_MASTER_PASSWORD=password

and

project.dev/config/database.php:

    'mysql_master' => [
        'driver'    => 'mysql',
        'host'      => env('DB_MASTER_HOST', 'localhost'),
        'port'      => env('DB_MASTER_PORT', '3306'),
        'database'  => env('DB_MASTER_DATABASE', 'forge'),
        'username'  => env('DB_MASTER_USERNAME', 'forge'),
        'password'  => env('DB_MASTER_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
        'engine'    => null,
    ],
    'mysql_slave'        => [
        'driver'    => 'mysql',
        'host'      => env('DB_SLAVE_HOST', 'localhost'),
        'database'  => env('DB_SLAVE_DATABASE', 'forge'),
        'username'  => env('DB_SLAVE_USERNAME', 'forge'),
        'password'  => env('DB_SLAVE_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

Then you can use method setConnection like that:

public function getIndex(Product $product)
{
    $this->products = $product->setConnection('mysql_slave')
        ->where('id' '>' 20)
        ->get()
...