Related content

Laravel provides a .env file for connecting different types of databases. In this tutorial, I will show you how to connect a remote MySQL database with an ssh tunnel in laravel application. I will show you step by step so that you can make it very easily without any confusion.

Sometimes we need to connect the server database to another server or in the local environment at that time we can use an ssh tunnel to connect the remote server database. ssh tunnel will allow connecting databases using the port. so let's follow bellow steps:

Step 1: Open SSH Tunnel

We can open the ssh tunnel using the ssh command below:

ssh -N -L 13306: [USER]@[SERVER_IP]


Now see the example code:

ssh -N -L 13306: root@111.111.111


Example with SSH Key:

ssh -i ./path/to/id_rsa -N -L 13306: root@111.111.111


Now we need to reliably keep an SSH tunnel open in the server. So run the below command:

ssh -f -N -L 13307: user_name@server_ip


Step 2: Add MySQL Configuration

Next, we need to add another MySQL configuration to the database.php file. so let's add the server MySQL database username and password on the .env file and use it in the database.php file:




Now update the database.php file like:


'server_mysql' => [
    'driver' => 'mysql',
    'host' => env('SERVER_DB_HOST', ''),
    'port' => env('SERVER_DB_PORT', '3306'),
    'database' => env('SERVER_DB_DATABASE', 'forge'),
    'username' => env('SERVER_DB_USERNAME', 'forge'),
    'password' => env('SERVER_DB_PASSWORD', ''),


Step 3: Fetch Remote Server Database

All are set to go now. Now we can fetch remote server data like:



Route::get('/test', function () {
    $records = \DB::connection('server_mysql')


Read also: How To Connect MySQL Database In PHP Laravel?



I have tried to discuss the clear concept of how to connect remote mysql database in laravel. Now we know laravel connect to remote database. Hope this how to connect remote mysql database in laravel tutorial will help you.