Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save akhileshdarjee/dc6cd5127433e746704bae2c68b70f32 to your computer and use it in GitHub Desktop.
Save akhileshdarjee/dc6cd5127433e746704bae2c68b70f32 to your computer and use it in GitHub Desktop.

Revisions

  1. akhileshdarjee created this gist Apr 22, 2019.
    64 changes: 64 additions & 0 deletions scheduling mysql backups with laravel.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,64 @@
    To manually dump the database you can run the following one-liner code

    mysqldump -u[user] -p[pass] [db] > [file_path]

    But what if you want to automate the process, here are the steps:

    1. Setup cron entry to your server
    * * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1

    2. Create a command BackupDatabase by running the following code:
    php artisan make:command BackupDatabase

    3. Navigate to app/Console/Commands/BackupDatabase.php and replace the code with the following:
    <?php

    namespace App\Console\Commands;

    use Illuminate\Console\Command;
    use Symfony\Component\Process\Process;
    use Symfony\Component\Process\Exception\ProcessFailedException;

    class BackupDatabase extends Command
    {
    protected $signature = 'db:backup';

    protected $description = 'Backup the database';

    protected $process;

    public function __construct()
    {
    parent::__construct();

    $this->process = new Process(sprintf(
    'mysqldump -u%s -p%s %s > %s',
    config('database.connections.mysql.username'),
    config('database.connections.mysql.password'),
    config('database.connections.mysql.database'),
    storage_path('app/backups/backup-' . time() . '.sql')
    ));
    }

    public function handle()
    {
    try {
    $this->process->mustRun();

    $this->info('The backup has been proceed successfully.');
    } catch (ProcessFailedException $exception) {
    $this->error('The backup process has been failed.');
    }
    }
    }

    ?>

    4. Schedule the backup task, navigate to app/Console/Kernel.php and append the following line of code inside schedule method to run database backups every Saturday at 11PM. You can set the frequency as per your requirements
    $schedule->command('db:backup')->saturdays()->at('23:00');

    5. Create backups directory inside storage/app directory and place a .gitignore file inside backups directory with the following code
    *
    !.gitignore

    That’s it you’ve now enabled weekly automated database backups in Laravel.