I am able to connect with another database like this
DB::connection('connection_2')->table("users")->get();
But this code is not working
User::connection('connection_2')->get();
You need to set the $connection
property of your model like so:
class MyModel extends Eloquent {
protected $connection = 'connection_2';
}
Add in database.php:
'main' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_MAIN', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false
],
'admin' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_ADMIN', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false
]
Then use:
DB::connection('main')->table("users")->get();
DB::connection('admin')->table("users")->get();
In your User.php
model:
class User extends Model
{
protected $connection = 'main';
protected $table = 'users';
protected $fillable = [
'id','name'
];
}
Then use:
User::get();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.