Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LARAVEL Eloquent query multiple schema

Do i need to create multiple connection to access different database/schema. Cant I use with one dbconnection. Is there a way to pass the database name in the laravel eloquent or db builder? Currently in raw php i use one connection to query the different schema.

like image 901
Arav Avatar asked Dec 14 '16 03:12

Arav


1 Answers

Create different connections to your database.php file and then pass them to your eloquent models.

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

// connection 2
'mysql2' => [
    'driver'    => 'mysql',
    'host'      => env('DB_HOST', 'localhost'),
    'database'  => 'db2',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
    'strict'    => false,
],

Suppose i have model User.php uses mysql connection named mysql1

inside my model i will add :

protected $connection = 'mysql1'; 

if i want to use mysql connection named mysql2 then i will use

protected $connection = 'mysql2'; 

Here i am setting connections statically in to models.

like image 117
Himanshu Raval Avatar answered Oct 03 '22 16:10

Himanshu Raval