You need config file .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database1
DB_USERNAME=root
DB_PASSWORD=secret
DB_CONNECTION_SECOND=mysql
DB_HOST_SECOND=127.0.0.1
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=database2
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=secret
Continue, open file config/database.php in folder config, add lists connection
'mysql' => [
'driver' => env('DB_CONNECTION'),
'host' => env('DB_HOST'),
'port' => env('DB_PORT'),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
],
'mysql2' => [
'driver' => env('DB_CONNECTION_SECOND'),
'host' => env('DB_HOST_SECOND'),
'port' => env('DB_PORT_SECOND'),
'database' => env('DB_DATABASE_SECOND'),
'username' => env('DB_USERNAME_SECOND'),
'password' => env('DB_PASSWORD_SECOND'),
],
when you edit success, you can using it
//shema in migration database
Schema::connection('mysql2')->create('some_table', function($table)
{
$table->increments('id'):
});
You can also define custom connection with query builder as shown below
DB::connection('mysql2')->select(...)->(...);
Using connection Model in Laravel Eloquent, you can add $connection to Model
class Post extends Model
{
protected $connection = 'mysql2';
}
In file PostController.php, you set connnection to database need using
user App\Post;
public function getAllPost()
{
$post = new Post;
$post->setConnection('mysql2');
$data = $post->find(1);
return $data;
}
Top comments (0)