PHPackages                             webmavens/laravel-remote-http-database - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. webmavens/laravel-remote-http-database

ActiveLibrary[HTTP &amp; Networking](/categories/http)

webmavens/laravel-remote-http-database
======================================

Laravel database adapter for remote MySQL via HTTP API with encryption

0.0.5(4mo ago)0108↓93.3%MITPHPPHP &gt;=7.4

Since Jan 25Pushed 4mo agoCompare

[ Source](https://github.com/webmavens/laravel-remote-http-database)[ Packagist](https://packagist.org/packages/webmavens/laravel-remote-http-database)[ RSS](/packages/webmavens-laravel-remote-http-database/feed)WikiDiscussions main Synced today

READMEChangelog (5)Dependencies (6)Versions (6)Used By (0)

Laravel Remote HTTP Database Adapter
====================================

[](#laravel-remote-http-database-adapter)

A Laravel package that provides a custom database adapter for communicating with a remote MySQL server via HTTP API. This allows you to run a Laravel application on a server without MySQL by connecting to a remote MySQL server through an encrypted HTTP endpoint.

Quick Start
-----------

[](#quick-start)

1. **Install on both servers**: `composer require webmavens/laravel-remote-http-database`
2. **Generate keys** (run once, use on both servers): ```
    php -r "echo 'REMOTE_DB_API_KEY=' . bin2hex(random_bytes(32)) . PHP_EOL;"
    php -r "echo 'REMOTE_DB_ENCRYPTION_KEY=' . base64_encode(random_bytes(32)) . PHP_EOL;"
    ```
3. **Server 1** (has MySQL): Set `REMOTE_DB_API_KEY` and `REMOTE_DB_ENCRYPTION_KEY` in `.env` (optionally add `REMOTE_DB_ALLOWED_IPS` for IP whitelisting)
4. **Server 2** (client):
    - **⚠️ REQUIRED: Manually add the `remote-http` connection to `config/database.php`** (see Step 4 below for the exact code)
    - Set `DB_CONNECTION=remote-http`, `DB_REMOTE_ENDPOINT`, `DB_REMOTE_API_KEY`, and `DB_REMOTE_ENCRYPTION_KEY` in `.env`

See the [Installation](#installation) section for detailed steps.

Features
--------

[](#features)

- 🔒 **Secure**: AES-256-GCM encryption for all data in transit
- 🔑 **Authenticated**: API key-based authentication
- 🛡️ **IP Whitelisting**: Optional IP address whitelisting for additional security
- 🔄 **Transaction Support**: Full transaction support with session-based state management
- 🚀 **Drop-in Replacement**: No code changes needed - just change your database connection
- ✅ **Full Compatibility**: Supports all Laravel database features (Eloquent, migrations, transactions, etc.)

Architecture
------------

[](#architecture)

```
Server 2 (No MySQL)                    Server 1 (Has MySQL)
┌─────────────────────┐                ┌─────────────────────┐
│ Laravel Application │                │ Remote Endpoint     │
│                     │                │                     │
│  Remote HTTP        │──HTTPS/API───▶│  MySQL Database     │
│  Database Adapter   │                │                     │
└─────────────────────┘                └─────────────────────┘

```

Requirements
------------

[](#requirements)

- PHP 7.4 or higher (tested up to PHP 8.5+)
- Laravel 10.x, 11.x, or 12.x
- Guzzle HTTP Client
- OpenSSL extension (for encryption)

Installation
------------

[](#installation)

### Step 1: Install the Package

[](#step-1-install-the-package)

Install the package on both servers via Composer:

```
composer require webmavens/laravel-remote-http-database
```

The service provider will be auto-discovered by Laravel, so no manual registration is needed.

### Step 2: Generate Security Keys

[](#step-2-generate-security-keys)

Generate a secure API key and encryption key. These must be **identical** on both servers:

```
# Generate a 32-byte encryption key (base64 encoded)
php -r "echo base64_encode(random_bytes(32));"

# Generate a secure API key (hex encoded, 64 characters)
php -r "echo bin2hex(random_bytes(32));"
```

Save these values - you'll need them for both servers.

### Step 3: Configure Server 1 (Has MySQL)

[](#step-3-configure-server-1-has-mysql)

Server 1 hosts the MySQL database and serves the remote endpoint.

1. **Configure your `.env` file** with your MySQL connection and security keys:

```
# Standard MySQL connection (for the endpoint to use)
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password

# Remote endpoint security keys (MUST match Server 2)
REMOTE_DB_API_KEY=your-generated-api-key-here
REMOTE_DB_ENCRYPTION_KEY=your-generated-encryption-key-here

# Optional: IP whitelist (comma-separated IP addresses)
# Only requests from these IPs will be allowed. Leave empty to allow all IPs.
REMOTE_DB_ALLOWED_IPS=192.168.1.100,10.0.0.50,203.0.113.45
```

**Important Notes:**

- The `REMOTE_DB_API_KEY` can be any secure string (recommended: 64+ characters)
- The `REMOTE_DB_ENCRYPTION_KEY` must be exactly 32 bytes when decoded. You can store it as:
    - Raw 32-byte string, OR
    - Base64-encoded string (44 characters) - the package will auto-detect and decode it
- **IP Whitelisting**: The `REMOTE_DB_ALLOWED_IPS` is optional. If set, only requests from the specified IP addresses will be allowed. Requests from other IPs will be rejected with a `403 Forbidden` response before any processing occurs. This provides an additional security layer.

2. **The endpoint route is automatically registered** at `/remote-db-endpoint` when `REMOTE_DB_API_KEY` is set.
3. **Test the endpoint** (optional):

```
curl http://localhost:8000/remote-db-endpoint
```

You should see a JSON response with endpoint information.

### Step 4: Configure Server 2 (No MySQL - Client)

[](#step-4-configure-server-2-no-mysql---client)

Server 2 connects to Server 1's endpoint to access the database.

**⚠️ IMPORTANT: Manual code edit required!** You must manually add the `remote-http` connection configuration to your `config/database.php` file. This cannot be done automatically.

1. **Add the remote-http connection to `config/database.php`**:

Open `config/database.php` and add the following connection to the `connections` array. **Important:** This configuration safely handles cases where `DB_REMOTE_ENDPOINT` is not set (e.g., on Server 1), preventing PHP deprecation warnings:

```
'connections' => [
    // ... other connections

    'remote-http' => [
        'driver' => 'remote-http',
        'endpoint' => env('DB_REMOTE_ENDPOINT'),
        'api_key' => env('DB_REMOTE_API_KEY'),
        'encryption_key' => (function() {
            $key = env('DB_REMOTE_ENCRYPTION_KEY');
            // Return null if key is not set (prevents deprecation warning on Server 1)
            if ($key === null) {
                return null;
            }
            // Try to decode base64, fallback to raw key if decoding fails or length is wrong
            $decoded = base64_decode($key, true);
            return ($decoded !== false && strlen($decoded) === 32) ? $decoded : $key;
        })(),
        'database' => env('DB_DATABASE', 'laravel'),
        'timeout' => env('DB_REMOTE_TIMEOUT', 30),
        'verify_ssl' => env('DB_REMOTE_VERIFY_SSL', true),
        'retry_attempts' => env('DB_REMOTE_RETRY_ATTEMPTS', 3),
        'enable_batching' => env('DB_REMOTE_ENABLE_BATCHING', true),
        'enable_caching' => env('DB_REMOTE_ENABLE_CACHING', true),
        'cache_ttl' => env('DB_REMOTE_CACHE_TTL', 60),
        'prefix' => '',
        'prefix_indexes' => true,
    ],
],
```

**Note:**

- The `encryption_key` configuration safely handles both base64-encoded and raw 32-byte keys automatically.
- It prevents PHP 8.1+ deprecation warnings when `DB_REMOTE_ENCRYPTION_KEY` is not set (e.g., on Server 1 which doesn't need this connection).
- The connection will only be used when `DB_REMOTE_ENDPOINT` is configured in your `.env` file.

2. **Configure your `.env` file**:

```
# Use remote-http as the default connection
DB_CONNECTION=remote-http

# Remote HTTP Database Configuration
DB_REMOTE_ENDPOINT=http://server1.example.com/remote-db-endpoint
DB_REMOTE_API_KEY=your-generated-api-key-here
DB_REMOTE_ENCRYPTION_KEY=your-generated-encryption-key-here
DB_DATABASE=your_database_name
DB_REMOTE_TIMEOUT=30
DB_REMOTE_VERIFY_SSL=true
DB_REMOTE_RETRY_ATTEMPTS=3

# Performance Optimization (optional)
DB_REMOTE_ENABLE_BATCHING=true
DB_REMOTE_ENABLE_CACHING=true
DB_REMOTE_CACHE_TTL=60
```

**Critical**: The `DB_REMOTE_API_KEY` and `DB_REMOTE_ENCRYPTION_KEY` must **exactly match** the values on Server 1.

3. **For local development**, you can disable SSL verification:

```
DB_REMOTE_VERIFY_SSL=false
```

**⚠️ Never disable SSL verification in production!**

### Step 5: Test the Connection

[](#step-5-test-the-connection)

Test the connection from Server 2:

```
php artisan tinker
```

```
DB::connection()->select('SELECT 1 as test');
```

Or create a test script:

```
