PHPackages                             yukazakiri/laravel-database-sync - 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. [Database &amp; ORM](/categories/database)
4. /
5. yukazakiri/laravel-database-sync

ActiveLibrary[Database &amp; ORM](/categories/database)

yukazakiri/laravel-database-sync
================================

Sync your production database in to your local database to start developing with production data

0.1.0(3mo ago)09MITPHPPHP ^8.2

Since Jan 30Pushed 3mo agoCompare

[ Source](https://github.com/yukazakiri/laravel-database-sync)[ Packagist](https://packagist.org/packages/yukazakiri/laravel-database-sync)[ Docs](https://github.com/yukazakiri/laravel-database-sync)[ RSS](/packages/yukazakiri-laravel-database-sync/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (4)Versions (3)Used By (0)

Laravel Database Sync
=====================

[](#laravel-database-sync)

> **Note**: This is a forked version of the original [Laravel Database Sync](https://github.com/marshmallow-packages/laravel-database-sync) package. This version has been enhanced with **PostgreSQL support** and optimized for real-world SSH and containerized workflows.

A powerful Laravel package that enables seamless synchronization of data from a remote database to your local development environment.

Table of Contents
-----------------

[](#table-of-contents)

- [Requirements](#requirements)
- [What's New in This Fork](#whats-new-in-this-fork)
- [Installation](#installation)
- [Configuration](#configuration)
    - [Environment Variables](#environment-variables)
- [Usage](#usage)
    - [Basic Synchronization](#basic-synchronization)
    - [Advanced Options](#advanced-options)
    - [Per-Table Sync Tracking](#per-table-sync-tracking)
    - [Table Configuration](#table-configuration)
    - [Timeout Configuration](#timeout-configuration)
    - [Synchronization Suites](#synchronization-suites)
    - [Multi-Tenant Support](#multi-tenant-support)
- [Testing](#testing)
    - [Test Structure](#test-structure)
    - [Writing Tests](#writing-tests)
- [Security](#security)
- [Support](#support)
- [License](#license)

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

[](#requirements)

- PHP ^8.2
- Laravel ^10.0|^11.0|^12.0

What's New in This Fork
-----------------------

[](#whats-new-in-this-fork)

This fork builds on the original PostgreSQL support with improvements focused on real-world SSH and containerized workflows:

- **Postgres schema bootstrapping**: If the local database is empty, the sync now pulls schema objects first (tables, enums, types) so data imports succeed.
- **Custom `pg_dump` binary**: You can point the sync to a Postgres 17 client binary on the remote host to avoid version mismatch errors.
- **Sail-friendly temp file location**: The default local dump path uses Laravel's `storage_path()` so it works inside Docker containers.
- **SSH port parsing for `scp`**: Custom SSH ports (e.g. `-p 25610`) are translated to `scp`'s `-P` flag automatically.
- **Stricter validation and debug output**: Dump, copy, and import steps now fail loudly when files are missing or empty to prevent silent no-op syncs.

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

[](#installation)

You can install the package via composer:

```
composer require yukazakiri/laravel-database-sync --dev
```

Configuration
-------------

[](#configuration)

Publish the configuration file:

```
php artisan vendor:publish --tag="database-sync-config"
```

### Environment Variables

[](#environment-variables)

Add these variables to your `.env` file:

```
# Database Driver (mysql or postgres)
DATABASE_SYNC_DATABASE_DRIVER=postgres

DATABASE_SYNC_REMOTE_USER_AND_HOST="forge@1.1.1.1"
DATABASE_SYNC_REMOTE_DATABASE_USERNAME=forge
DATABASE_SYNC_REMOTE_DATABASE_PASSWORD=

DATABASE_SYNC_TEMPORARY_FILE_LOCATION_REMOTE=~/new_data.sql
DATABASE_SYNC_TEMPORARY_FILE_LOCATION_LOCAL=/path/to/your/app/storage/new_data.sql

# Postgres-specific options
DATABASE_SYNC_POSTGRES_PG_DUMP_BINARY=/usr/lib/postgresql/17/bin/pg_dump
DATABASE_SYNC_POSTGRES_SCHEMA_DUMP_FLAGS="--schema-only --no-owner --no-privileges"
DATABASE_SYNC_POSTGRES_CREATE_MISSING_TABLES=true
```

> **Important**: When connecting to a Forge-provisioned database server, you must use the main database user that was created during the initial server provisioning. Other database users created afterward may not have the necessary privileges to execute the required database commands for synchronization.

Usage
-----

[](#usage)

### PostgreSQL Support

[](#postgresql-support)

This package supports PostgreSQL in addition to MySQL. To use PostgreSQL:

1. Set `DATABASE_SYNC_DATABASE_DRIVER=postgres` in your `.env`.
2. Ensure PostgreSQL client tools (`psql`, `pg_dump`) are installed on both local and remote systems.
3. (Optional) Customize dump flags in `config/database-sync.php`:

```
'postgres' => [
    'dump_action_flags' => '--no-owner --no-privileges --data-only --column-inserts --on-conflict-do-nothing',
],
```

#### Migration from MySQL

[](#migration-from-mysql)

To migrate an existing MySQL setup to PostgreSQL:

1. Update your database connections to PostgreSQL.
2. Set `DATABASE_SYNC_DATABASE_DRIVER=postgres` in your environment.
3. Ensure PostgreSQL client tools are installed.
4. Run the sync command as usual.

### Basic Synchronization

[](#basic-synchronization)

To sync your remote database to local:

```
php artisan db-sync
```

By default, the package uses **batch file transfers** for optimal performance, transferring all table data in a single file to minimize network overhead.

### Advanced Options

[](#advanced-options)

The sync command supports several options:

```
php artisan db-sync [options]
```

Available options:

- `--date`: Sync records from a specific date
- `--suite`: Use a predefined suite of tables
- `--table`: Sync a specific table
- `--tenant`: Specify tenant for multi-tenant applications
- `--skip-landlord`: Skip landlord database in multi-tenant setup
- `--full-sync`: Sync the full table without a date constraint
- `--status`: View the sync history and status for all tables
- `--individual-transfers`: Use individual file transfers for each table (legacy behavior)

### Per-Table Sync Tracking

[](#per-table-sync-tracking)

The package now tracks the last sync date for each individual table, preventing data loss when syncing single tables. This means:

- Each table maintains its own sync history
- When syncing a specific table with `--table`, only that table's sync date is considered
- The package automatically falls back to the global sync date for backward compatibility
- You can view the sync status of all tables using the `--status` option
- **Sync timestamps are captured at the start of the process to prevent missing data created during sync**

#### Viewing Sync Status

[](#viewing-sync-status)

To see the last sync date for all tables:

```
php artisan db-sync --status
```

This will display a table showing each table name and its last sync date, helping you track which tables have been synced recently and which might need attention.

#### How It Works

[](#how-it-works)

1. **Sync Start Timestamp**: The sync timestamp is captured when the sync process begins
2. **Individual Table Tracking**: Each table's sync date is stored separately in the cache file
3. **Atomic Updates**: Cache is only updated when the entire sync process completes successfully
4. **Automatic Fallback**: If no table-specific date exists, the global sync date is used
5. **Backward Compatibility**: Existing installations continue to work without any changes
6. **Debug Information**: When running with `-vvv` (debug mode), you'll see which sync date is being used for each table
7. **Error Recovery**: If sync fails, the cache remains unchanged with the previous sync dates

### File Transfer Optimization

[](#file-transfer-optimization)

The package uses **batch file transfers** by default to minimize network overhead:

- **Batch Mode (Default)**: All tables are dumped to a single file and transferred once
- **Individual Mode**: Each table is transferred separately (legacy behavior)

#### Configuration

[](#configuration-1)

Control the transfer mode in `config/database-sync.php`:

```
'file_transfer_mode' => 'batch', // or 'individual'
```

Or via environment variable:

```
DATABASE_SYNC_FILE_TRANSFER_MODE=batch
```

#### Benefits of Batch Transfer

[](#benefits-of-batch-transfer)

- **Reduced network overhead**: Single file transfer instead of multiple
- **Faster sync times**: Especially noticeable with many tables
- **Better compression**: SSH compression works more efficiently on larger files
- **Lower resource usage**: Fewer process spawns and file operations

#### When Individual Transfers Are Used

[](#when-individual-transfers-are-used)

- Single table sync (`--table=tablename`)
- Explicit override (`--individual-transfers`)
- Config set to `individual` mode

### Table Configuration

[](#table-configuration)

You can exclude specific tables from synchronization in the `config/database-sync.php` file:

```
'tables' => [
    'ignore' => [
        'action_events',
        'jobs',
        'telescope_entries',
        'password_resets',
    ],
],
```

### Timeout Configuration

[](#timeout-configuration)

For large databases, you may need to adjust the process timeout to prevent operations from timing out:

```
// Set timeout in seconds (default: 300 seconds / 5 minutes)
'process_timeout' => 600, // 10 minutes

// Or set to null to disable timeout entirely for very large databases
'process_timeout' => null,
```

You can also set this via environment variable:

```
DATABASE_SYNC_PROCESS_TIMEOUT=600
```

This timeout applies to:

- MySQL dump operations (`mysqldump`)
- MySQL import operations (`mysql`)
- File transfer operations (`scp`)

### Synchronization Suites

[](#synchronization-suites)

Define custom synchronization suites in the configuration file to group tables for specific sync tasks:

```
'suites' => [
    'orders' => [
        'orders',
        'order_items',
    ],
],
```

Then use the suite option:

```
php artisan db-sync --suite=orders
```

### Multi-Tenant Support

[](#multi-tenant-support)

The package supports multi-tenant architectures. Enable it in the configuration:

```
'multi_tenant' => [
    'landlord' => [
        'database_name' => 'yukazakiri_landord',
        'tables' => [
            'ignore' => [
                'action_events',
            ],
        ],
    ],
    'tenants' => [
        'database_names' => [
            'yukazakiri_nl' => [
                'tables' => [
                    'ignore' => [
                        'users',
                    ],
                ],
            ],
            'yukazakiri_dev',
            'yukazakiri_io',
        ],
        'tables' => [
            'ignore' => [
                'logs',
            ],
        ],
    ],
],
```

Configure tenant-specific settings in your configuration file and use the `--tenant` option to sync specific tenant databases:

```
php artisan db-sync --tenant="yukazakiri_nl" --skip-landlord
php artisan db-sync --tenant="yukazakiri_nl" --skip-landlord --suite=orders
```

Testing
-------

[](#testing)

This package uses Pest PHP for testing. To run the tests:

```
composer test
```

To run tests with coverage report:

```
composer test-coverage
```

### Test Structure

[](#test-structure)

The test suite includes:

- **Unit Tests**: Testing individual components

    - `Config` class tests
    - `DatabaseSync` class tests
    - Other utility classes
- **Feature Tests**: Testing the package functionality

    - Command execution tests
    - Multi-tenant functionality
    - Suite configurations
    - Table filtering

### Writing Tests

[](#writing-tests)

To add new tests, create a new test file in either the `tests/Unit` or `tests/Feature` directory. The package uses Pest's expressive syntax:

```
test('your test description', function () {
    // Your test code
    expect($result)->toBe($expected);
});
```

Security
--------

[](#security)

- Never commit sensitive database credentials to version control
- Always use environment variables for sensitive information
- Ensure proper access controls on both remote and local databases

Support
-------

[](#support)

For support, please email

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance81

Actively maintained with recent releases

Popularity5

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 Bus Factor1

Top contributor holds 82% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

102d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/6f597a96c5e003ede3808ec960400b3598aea698b26e8cd6a3491af5a7c2cb01?d=identicon)[yukazakiri](/maintainers/yukazakiri)

---

Top Contributors

[![stefvanesch](https://avatars.githubusercontent.com/u/46725619?v=4)](https://github.com/stefvanesch "stefvanesch (50 commits)")[![yukazakiri](https://avatars.githubusercontent.com/u/128908897?v=4)](https://github.com/yukazakiri "yukazakiri (10 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

---

Tags

laravelyukazakiri

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/yukazakiri-laravel-database-sync/health.svg)

```
[![Health](https://phpackages.com/badges/yukazakiri-laravel-database-sync/health.svg)](https://phpackages.com/packages/yukazakiri-laravel-database-sync)
```

###  Alternatives

[tpetry/laravel-postgresql-enhanced

Support for many missing PostgreSQL specific features

9982.0M14](/packages/tpetry-laravel-postgresql-enhanced)[anourvalar/eloquent-serialize

Laravel Query Builder (Eloquent) serialization

11320.2M21](/packages/anourvalar-eloquent-serialize)[biiiiiigmonster/hasin

Laravel framework relation has in implement

154552.4k](/packages/biiiiiigmonster-hasin)[dragon-code/laravel-deploy-operations

Performing any actions during the deployment process

240173.5k2](/packages/dragon-code-laravel-deploy-operations)[bavix/laravel-clickhouse

Eloquent model for ClickHouse

72214.1k2](/packages/bavix-laravel-clickhouse)[stayallive/laravel-eloquent-observable

Register Eloquent model event listeners just-in-time directly from the model.

2928.9k7](/packages/stayallive-laravel-eloquent-observable)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
