Laravel Connect Remote Database using SSH Tunnel

Laravel Connect Remote Database using SSH Tunnel

To connect remote database using ssh tunnel in laravel; Through this tutorial, we will learn how to connect remote database using ssh tunnel in laravel applications.

Sometime we need to connect server database in another server or in local environment at that time we can use ssh tunnel to connect remote server database. ssh tunnel will allows to connect database using port.

Laravel Connect Remote Database using SSH Tunnel

Use 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;

.env

...
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

Execute the following command on terminal to start development server; as follows:

php artisan serve
Recommended:-Laravel Try Catch

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *