Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 Automatic Daily Database Backup Example

Last Updated on May 13, 2024 by

In this tutorial guide, I will show you step by step how to set up automatic daily, weekly, monthly database backup using cron job command in laravel.

Let’s start by creating a cron job command and set up it to take automatic daily, weekly, monthly database backups:

Step 1: Install Laravel 11

If you do not have laravel 11 set up into your system, run the following command to install it:

composer create-project laravel/laravel blog

Step 2: Create the Command

Run the following Artisan command to generate the command class:

php artisan make:command BackUpDB

Step 3: Implement the Command Logic

Edit the BackUpDB.php file from app/Console/Commands directory, and in the handle() method, implement the logic to backup the database:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class BackUpDB extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'database:backup';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $filename = "backup-" . now()->format('Y-m-d') . ".gz";
    
        $command = "mysqldump --user=" . env('DB_USERNAME') ." --password=" . env('DB_PASSWORD') . " --host=" . env('DB_HOST') . " " . env('DB_DATABASE') . "  | gzip > " . storage_path() . "/app/backup/" . $filename;
    
        $returnVar = NULL;
        $output  = NULL;
    
        exec($command, $output, $returnVar);
    }
}

Step 4: Create DB Backup Directory

Create directory named backup in storage/app directory, to store database backup in it.

Step 5: Schedule the Command

Edit the app/Console/Kernel.php file, In the schedule() method, add a new scheduled task that calls your command:

<?php

use Illuminate\Support\Facades\Schedule;

Schedule::command('database:backup')->daily();

Step 6: Configure Task Scheduling

To setup a cronjob on the server that handles the execution of the schedule: Run the command at regular intervals, it will take a backup of the database and store it in the storage folder:

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

Leave a Comment