Looking to hire Laravel developers? Try LaraJobs

laravel-clone maintained by phpawcom

Description
Back up, restore and clone a Laravel app's database (and optionally storage) between servers with Artisan commands.
Author
Last update
2026/12/02 19:41 (dev-main)
License
Links
Downloads
7

Comments
comments powered by Disqus

Laravel Clone

Latest Version on Packagist Total Downloads License

Back up, restore and clone a Laravel app's database — and optionally its storage files — between servers, with four Artisan commands.

Written by Claude. This package, including all of its code and documentation, was written entirely by Claude, Anthropic's AI model. Review it as you would any third-party code, and test backups and restores on a non-production copy before you rely on them.

php artisan clone:backup --storage            # archive DB + storage/app
php artisan clone:restore --storage           # restore the latest archive
php artisan clone:pull production --storage   # copy production into this server over SSH
php artisan clone:list                        # see what you have
php artisan clone                             # guided menu for all of the above
  • MySQL / MariaDB, PostgreSQL and SQLite
  • One file per backup: *.clone.tar holds a manifest, the compressed dump and (optionally) the compressed storage
  • Safe by default: asks for confirmation, takes a safety backup before overwriting, refuses to mix database drivers
  • Built for shared hosting / cPanel: strips DEFINERs, avoids the PROCESS privilege error, keeps passwords off the command line
  • Big-table friendly: keep the structure of log tables (Telescope, Pulse, …) but skip their rows
  • Sanitizers to anonymise data when cloning production into staging

Requires PHP 8.2+, Laravel 11, 12 or 13, and bash, tar and gzip on the server (any Linux or macOS host). It also needs the client tools for your database: mysqldump/mysql (or mariadb-dump/mariadb), or pg_dump/psql. SQLite needs nothing extra.

Installation

Install it in every app you want to clone from or to: clone:pull runs clone:backup on the remote server, so the package must be there too.

1. Require the package

The package is on Packagist. In your app's root folder:

composer require phpawcom/laravel-clone

Laravel discovers the service provider automatically; there is nothing to register.

2. Publish the config (optional)

php artisan vendor:publish --tag=clone-config

This creates config/clone.php, where you define remotes for clone:pull, tables whose rows to skip, storage paths, retention and sanitizers. The defaults work without it.

3. Check it works

php artisan list clone     # shows clone:backup, clone:restore, clone:pull, clone:list
php artisan clone:backup   # creates your first archive in storage/app/clones

Updating

composer update phpawcom/laravel-clone

Releases are listed on Packagist and the GitHub releases page.

Commands

clone (interactive)

php artisan clone

A guided menu for everything below: pick pull, backup, restore or list, then answer a few questions with the arrow keys. Pull offers your configured remotes (or lets you type [user@]host:/path), restore lists your archives with their source, database, size and whether they include storage.

Before it runs, it prints the equivalent command, for example php artisan clone:pull production --storage --ssh-prompt, so you can reuse it in scripts. Pull and restore always ask for a final confirmation. The wizard only collects your answers and then runs the matching clone:* command, so both behave exactly the same.

clone:backup

php artisan clone:backup                           # database only
php artisan clone:backup --storage                 # database + storage/app
php artisan clone:backup --name=before-upgrade     # label in the file name
php artisan clone:backup --exclude-data=audits     # keep the table, skip its rows
php artisan clone:backup --output=/backups/app.clone.tar
php artisan clone:backup --keep=5                  # retention for this run

Archives are written to storage/app/clones as {app}_{env}_{Ymd-His}[_label].clone.tar. The folder gets its own .gitignore and is never included in storage backups.

clone:restore

php artisan clone:restore                          # latest archive
php artisan clone:restore myapp_production_20261202-101500.clone.tar --storage
php artisan clone:restore /path/to/file.clone.tar --migrate --down
Option
--storage Also restore storage files (the archive must contain them)
--merge-storage Keep local files that aren't in the archive (default: replace the folders)
--migrate Run migrate --force afterwards (destination code is newer than the source)
--down Maintenance mode while restoring
--sanitize / --no-sanitize Override clone.sanitize.enabled
--no-safety-backup Skip the backup of the current state
--skip-after Skip storage:link, optimize:clear, queue:restart
--connection= Restore into another connection
--force No confirmation (required in non-interactive runs)

What happens:

  1. It shows the archive's source (app, env, host, database) and asks for confirmation.
  2. It backs up the current state as …_pre-restore.clone.tar. If something goes wrong, php artisan clone:restore with no argument restores that backup.
  3. It wipes the database (db:wipe, including views/types) and imports the dump.
  4. It replaces (or merges) the storage paths stored in the archive.
  5. It runs migrations, sanitizers and the post-restore commands.

clone:pull

Creates a backup on a remote server over SSH, downloads it, removes the temporary file from the remote and restores it locally.

php artisan clone:pull                                   # the default remote
php artisan clone:pull production --storage --sanitize   # a named remote
php artisan clone:pull myserver:/home/cpuser/app          # a ~/.ssh/config Host alias
php artisan clone:pull cpuser@server.example.com:/home/cpuser/app --port=2222 --php=php8.3

It accepts the same restore options as clone:restore, plus --remote-connection=, --delete-archive, --port=, --php=, --identity=, --ssh-config= and --ssh-prompt.

Remotes in .env

You can set up remotes in .env without publishing the config. List their names in CLONE_REMOTES, then set CLONE_{NAME}_* for each one:

CLONE_REMOTES=production            # comma-separated: production,staging
CLONE_REMOTE=production             # default for `clone:pull` with no argument

CLONE_PRODUCTION_HOST=server.example.com   # or a Host alias from ~/.ssh/config
CLONE_PRODUCTION_PATH=/home/cpuser/app     # remote Laravel root
CLONE_PRODUCTION_USER=cpuser               # optional
CLONE_PRODUCTION_PORT=22                   # optional
CLONE_PRODUCTION_PHP=/opt/cpanel/ea-php83/root/usr/bin/php
CLONE_PRODUCTION_IDENTITY_FILE=~/.ssh/id_ed25519   # optional
CLONE_PRODUCTION_SSH_CONFIG=                # optional: another ssh config file (-F)
CLONE_PRODUCTION_CONNECTION=                # optional: remote DB connection
CLONE_PRODUCTION_TRANSFER=scp               # scp | rsync (resumable; needs rsync on both ends)
CLONE_PRODUCTION_SSH_OPTIONS="-o StrictHostKeyChecking=accept-new"
CLONE_PRODUCTION_SSH_PROMPT=false           # true: SSH may ask for a password or passphrase

Only HOST and PATH are required. With a single remote, CLONE_REMOTE isn't needed. The values are read when the config loads, so php artisan config:cache keeps working.

Remotes in config/clone.php

'remotes' => [
    'production' => [
        'host' => 'server.example.com',
        'user' => 'cpuser',
        'port' => 22,
        'path' => '/home/cpuser/app',
        'php' => '/opt/cpanel/ea-php83/root/usr/bin/php',
        'identity_file' => '~/.ssh/id_ed25519',
        'transfer' => 'scp', // or 'rsync'
        'ssh_prompt' => false, // true: SSH may ask for a password or passphrase
    ],
],

A remote defined here wins over a .env remote with the same name. If you published the config before .env remotes existed, add ...Phpawcom\LaravelClone\Support\EnvRemote::all(env('CLONE_REMOTES')), at the top of remotes and add 'default_remote' => env('CLONE_REMOTE'), above remotes.

Using your ~/.ssh

clone:pull runs your system's ssh/scp as the user who runs Artisan, so ~/.ssh/config, your keys, ssh-agent and ~/.ssh/known_hosts all apply. Leave user, port and identity_file out and SSH takes them from ~/.ssh/config:

# ~/.ssh/config
Host myserver
    HostName server.example.com
    User cpuser
    Port 2222
    IdentityFile ~/.ssh/id_ed25519
CLONE_REMOTES=production
CLONE_PRODUCTION_HOST=myserver
CLONE_PRODUCTION_PATH=/home/cpuser/app

Anything you set explicitly (in .env, the config or an option) overrides ~/.ssh/config. Run ssh myserver once by hand to accept the host key.

Passwords and key passphrases

By default SSH runs with BatchMode=yes, so it never stops at a prompt: use a key without a passphrase, or load it into ssh-agent. If the server needs a password, or your key has a passphrase, use --ssh-prompt (or ssh_prompt / CLONE_{NAME}_SSH_PROMPT=true):

php artisan clone:pull production --ssh-prompt

clone:pull then opens one SSH connection in your terminal, where you type the password once. The remote backup, the download and the cleanup all reuse that connection (SSH connection sharing, ControlMaster), and it is closed at the end. This needs an interactive terminal, so don't use it in cron or CI.

clone:list

Lists archives with their creation date, source, database, whether storage is included, and size.

Configuration highlights

'exclude_table_data' => ['telescope_entries', 'pulse_entries', /* … */], // tables that don't exist are ignored
'storage' => [
    'paths' => ['storage/app'],                 // add e.g. 'public/uploads'
    'exclude' => ['storage/app/livewire-tmp'],
],
'keep' => 10,                                    // archives kept after each backup
'mysql' => [
    'strip_definers' => true,
    'dump_options' => [],                        // e.g. ['--column-statistics=0']
],

storage/framework and storage/logs are deliberately left out, because caches, sessions, compiled views and logs belong to each server.

Sanitizers (production → staging)

namespace App\Clone;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Phpawcom\LaravelClone\Contracts\Sanitizer;

class AnonymiseUsers implements Sanitizer
{
    public function sanitize(string $connection, Command $command): void
    {
        $db = DB::connection($connection);

        $db->table('users')->where('is_admin', false)
            ->update(['email' => DB::raw("concat('user', id, '@example.test')")]);

        $db->table('jobs')->delete();
        $db->table('failed_jobs')->delete();
    }
}
'sanitize' => [
    'enabled' => env('CLONE_SANITIZE', false),
    'sanitizers' => [App\Clone\AnonymiseUsers::class],
],

Set CLONE_SANITIZE=true only in the staging/local .env. Sanitizing is off by default, so a production restore is never anonymised by accident.

Things to know

  • APP_KEY: encrypted casts and Crypt:: values only decrypt with the source app's key. A restore warns you when the keys differ. Copy the source APP_KEY if you need that data.
  • Same driver only: a MySQL archive restores into MySQL or MariaDB, and PostgreSQL into PostgreSQL. Cross-driver conversion isn't supported.
  • PostgreSQL: pg_dump must be the same major version as the server or newer. The dump runs with --no-owner --no-privileges. COMMENT ON EXTENSION lines are removed so non-superusers can restore databases that use extensions like pgvector. The extension itself must already be available on the destination server.
  • MySQL TLS: PDO::MYSQL_ATTR_SSL_CA/CERT/KEY from your connection's options are passed to mysqldump/mysql, so client-certificate connections work.
  • Credentials go into a temporary 0600 option file (MySQL) or libpq environment variables (PostgreSQL). They never appear in ps output.
  • Disk space: a backup or restore temporarily needs roughly twice the archive size in the archive folder.
  • Windows: not supported for MySQL/PostgreSQL, because the dump pipeline uses bash.

Credits

Written entirely by Claude (Anthropic), for phpawcom.

License

MIT