Step 1. In the env file write the code as below.
DB_CONNECTION_SECOND=mysql
DB_HOST_SECOND=127.0.0.1
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=gms2
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=
Step 2. In the database.php write the code as below.
'mysql2' => [
'driver' => env('DB_CONNECTION_SECOND'),
'host' => env('DB_HOST_SECOND', '127.0.0.1'),
'port' => env('DB_PORT_SECOND', '3306'),
'database' => env('DB_DATABASE_SECOND', 'forge'),
'username' => env('DB_USERNAME_SECOND', 'forge'),
'password' => env('DB_PASSWORD_SECOND', ''),
'unix_socket' => '',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
],
Step 3. In the model file add a line as below.
protected $connection = 'mysql2';
Step 4.
use App\Models\User;
class UsersController extends BaseController
{
public function getRecord()
{
$users = new Users;
$users->setConnection('mysql2');
$find = $users->find(1);
return $find;
}
}
With Query Builder
$users = DB::connection('mysql2')->table("users")->get();