sgupta1979's avatar

Cross server Database operations

Hello Team,

In my application ... I am using Laravel 10. In one module I need to insert records into a database table which is hosted on another server.

Can you please guide me .. what will be the best possible and secure solution to achieve this?

If you can share patch of code ... it will be really helpful.

Thanks

0 likes
1 reply
LaryAI's avatar
Level 58

To perform cross-server database operations in Laravel, you can configure multiple database connections in your config/database.php file and then use these connections in your models or queries. Here’s a step-by-step guide to achieve this:

  1. Configure Multiple Database Connections:

    Open your config/database.php file and add a new connection for the remote database. For example:

    Make sure to add the corresponding environment variables in your .env file:

    REMOTE_DB_HOST=remote_host
    REMOTE_DB_PORT=3306
    REMOTE_DB_DATABASE=remote_db
    REMOTE_DB_USERNAME=remote_user
    REMOTE_DB_PASSWORD=remote_password
    
  2. Using the Remote Connection:

    You can use the remote connection in your models or directly in your queries. Here’s an example of how to insert records into a table on the remote server:

    use Illuminate\Support\Facades\DB;
    
    class SomeController extends Controller
    {
        public function insertIntoRemoteDatabase()
        {
            $data = [
                'column1' => 'value1',
                'column2' => 'value2',
                // Add other columns and values as needed
            ];
    
            DB::connection('remote_mysql')->table('your_table')->insert($data);
    
            return response()->json(['message' => 'Data inserted successfully']);
        }
    }
    
  3. Using Eloquent with Remote Connection:

    If you prefer using Eloquent, you can define a model that uses the remote connection:

    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    
    class RemoteModel extends Model
    {
        protected $connection = 'remote_mysql';
        protected $table = 'your_table';
    
        // Define other model properties and methods as needed
    }
    

    Then, you can use this model to insert records:

    use App\Models\RemoteModel;
    
    class SomeController extends Controller
    {
        public function insertIntoRemoteDatabase()
        {
            $data = [
                'column1' => 'value1',
                'column2' => 'value2',
                // Add other columns and values as needed
            ];
    
            RemoteModel::create($data);
    
            return response()->json(['message' => 'Data inserted successfully']);
        }
    }
    

By following these steps, you can securely and efficiently perform cross-server database operations in your Laravel application.

Please or to participate in this conversation.