How to Create Database Backup in Laravel

In this article, we will discuss “How to Create Database Backup in Laravel”. In this, we are not going to use any additional package. We will create our artisan command for DB backup and schedule the same for daily or our desired time.

Database backup is a basic requirement of each project where we use a database. So we maintain the different services to take database backup. Some of the hosting providers, provide us daily backup for databases and files.

Create Laravel Project

Use the following composer command to install the fresh copy of Laravel.

composer create-project laravel/laravel laravel-project --prefer-dist

Establish Connection with DB

Open the “.env” file, located at the root of the Laravel project, and update the required DB credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel8
DB_USERNAME=root
DB_PASSWORD=root

Create Artisan Command

Run the following artisan command on the terminal.

php artisan make:command DatabaseBackup

You can get more details on Artisan Custom Command here.

Open the command file “DatabaseBackup.php” located at “app/Console/Commands”. Update the file as per the following code snippet.

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Carbon\Carbon;
use File;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create copy of mysql dump for existing database.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $filename = "backup-" . Carbon::now()->format('Y-m-d') . ".sql";

        // Create backup folder and set permission if not exist.
        $storageAt = storage_path() . "/app/backup/";
        if(!File::exists($storageAt)) {
            File::makeDirectory($storageAt, 0755, true, true);
        }

        $command = "".env('DB_DUMP_PATH', 'mysqldump')." --user=" . env('DB_USERNAME') ." --password=" . env('DB_PASSWORD') . " --host=" . env('DB_HOST') . " " . env('DB_DATABASE') . "  | gzip > " . $storageAt . $filename;

        $returnVar = NULL;
        $output = NULL;
        exec($command, $output, $returnVar);
    }
}

As you have seen, the “handle” function contains the backup command. First, we create a backup file name and then create a backup folder in the Laravel storage path if not exist.

Execute Artisan Command

Use the following artisan command on the terminal to test the database backup.

php artisan database:backup

After executing the above mention command, our DB backup file is created at “storage/app/backup”.


Schedule Database Backup Command as CRON

Open the “Kernel.php” located at “app\Console”. Update the schedule function as follows.

$schedule->command('database:backup')->daily();

Setup CRON on Server

At last, we are ready to setup the CRON on the server. Use the following command on the server terminal.

crontab -e

This will open the crontab, you have to add the CRON command here. For example:

* * * * * php /path/to/artisan schedule:run 1>> /dev/null 2>&1

OR

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

You can get more details on the Laravel Task Scheduling here.

Conclusion

In this article, we are discussing “How to Create Database Backup in Laravel”. Hope you like this article, and get basic exposure on Laravel Database Backup, Custom Artisan Command, and Task Scheduling. We will discuss more on Laravel, and etc. Please feel free to add comments if any queries or suggestions.

Keep Learning & Stay Safe 🙂

If you like our content, please consider buying us a coffee.
Thank you for your support!
Buy Me a Coffee

AWS S3 BucketLaravelLaravel Code Snippet
Comments (0)
Add Comment