Laravel Connect Remote Database using SSH Tunnel

Laravel connect remote database using ssh tunnel; In this tutorial, i am going to show you step by step how to connect remote database using ssh tunnel in laravel apps.

Laravel Connect Remote Database using SSH Tunnel

Follow the following steps to connect remote database using ssh tunnel in laravel applications; as follows:

  • Step 1: Open SSH Tunnel
  • Step 2: Configure MySQL Database
  • Step 3: Connect to Remote Server Database
  • Step 4: Start Development Server

Step 1: Open SSH Tunnel

Open ssh tunnel using the following ssh command; as follows:

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

For example:

ssh -N -L 13306:127.0.0.1:3306 [email protected]

Example with SSH Key:

ssh -i ./path/to/id_rsa -N -L 13306:127.0.0.1:3306 [email protected]

The ssh tunnel will open, but if you want to keep alive open that ssh tunnel then you can follow the below given steps.

Step 2: Configure MySQL Database

Configure mysql database details in laravel applications; sot open .evn file and database.php file;

...
SERVER_DB_CONNECTION=mysql
SERVER_DB_HOST=127.0.0.1
SERVER_DB_PORT=13306
SERVER_DB_DATABASE=laravel_demo
SERVER_DB_USERNAME=demo
SERVER_DB_PASSWORD=demo123456
...

config/database.php

  
...
'server_mysql' => [
    'driver' => 'mysql',
    'host' => env('SERVER_DB_HOST', '127.0.0.1'),
    '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: Connect to Remote Server Database

Create simple route and get server database table records and print it. So open web.php file and add the following routes into it; as follows:

Route::get('/server-db', function () {
  
    $records = \DB::connection('server_mysql')
            ->table('products')
            ->get()
            ->toArray();
  
    dd($records);
});

Step 4: Start Development Server

Run the following command on command prompt to start development server; as follows:

php artisan serve

Recommended Laravel Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.