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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With