← All Insights

Laravel: Copy Database Tables to Another Server

There are scenarios where you need to replicate database records to another server in real time, for reporting databases, read replicas, or data synchronization between environments.

The ideal approach is often binary replication at the database level. But when your hosting provider does not support binary logging or federated storage engines, you need an application-layer solution.

Laravel's Observer pattern provides a clean way to handle this without complex infrastructure.


The Problem

I needed real-time table replication between two database servers. The hosting provider rejected binary logging and federated storage engine approaches, leaving application-level synchronization as the only option.

The requirements were straightforward:

  • When a record is created locally, create the same record on the remote server
  • When a record is updated locally, update the same record on the remote server
  • No manual intervention required

Step 1: Configure the Remote Database Connection

Add a separate MySQL connection in config/database.php pointing to the replica server:

'replica' => [
    'driver'    => 'mysql',
    'host'      => env('REPLICA_DB_HOST', '127.0.0.1'),
    'port'      => env('REPLICA_DB_PORT', '3306'),
    'database'  => env('REPLICA_DB_DATABASE', 'forge'),
    'username'  => env('REPLICA_DB_USERNAME', 'forge'),
    'password'  => env('REPLICA_DB_PASSWORD', ''),
    'charset'   => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix'    => '',
    'strict'    => true,
    'engine'    => null,
],

Add the corresponding environment variables to your .env file for the remote server's credentials.


Step 2: Create a Remote Model

Create a dedicated Eloquent model that targets the remote database connection:

class RemoteOrder extends Model
{
    protected $connection = 'replica';
    protected $table = 'orders';
    public $timestamps = false;
}

This model behaves exactly like a normal Eloquent model, but all queries run against the replica connection instead of the default database.


Step 3: Create an Observer

Laravel Observers listen to model events and trigger actions when they occur. Create an observer in App\Http\Observers:

class OrderObserver
{
    public function created(Order $order)
    {
        $remote = new RemoteOrder();
        foreach ($order->toArray() as $key => $value) {
            if (!is_array($value)) {
                $remote->$key = $value;
            }
        }
        $remote->save();
    }

    public function updated(Order $order)
    {
        $remote = RemoteOrder::find($order->id);
        if ($remote) {
            foreach ($order->toArray() as $key => $value) {
                if (!is_array($value)) {
                    $remote->$key = $value;
                }
            }
            $remote->save();
        }
    }
}

The observer iterates over the model's attributes, skipping nested arrays (which would be relationships), and mirrors the values to the remote model.


Step 4: Register the Observer

Register the observer in the model's boot() method:

class Order extends Model
{
    protected static function boot()
    {
        parent::boot();
        Order::observe(OrderObserver::class);
    }
}

From this point on, every time an Order record is created or updated, the observer fires and replicates the change to the remote server automatically.


Considerations

This approach works reliably for straightforward replication scenarios, but there are things to keep in mind:

  • Network failures: If the remote database is unreachable, the observer will throw an exception. Consider wrapping the remote operations in a try/catch and queuing failed replications for retry.
  • Performance: Each create/update adds a remote database call. For high-write applications, this adds latency. Consider queuing the replication using Laravel's queue system.
  • Deletions: Add a deleted() method to the observer if you need to replicate deletes as well.
  • Initial sync: This approach handles ongoing changes but does not migrate existing data. You will need a one-time migration script for the initial data transfer.

Conclusion

Laravel's Observer pattern provides a clean application-layer solution for database replication when infrastructure-level options are not available.

The implementation is lightweight, follows Laravel conventions, and keeps the replication logic contained in a dedicated observer class rather than scattered across your application code. For environments where server-level replication is not an option, this approach delivers real-time synchronization with minimal complexity.