Laravel 9 Daily Weekly Monthly Automatic Database Backup

Share this Article
Reading Time: 7 minutes
229 Views

Inside this article we will see the concept i.e Laravel 9 Daily Weekly Monthly Automatic Database Backup. Article contains the classified information about creating database backup in laravel 9 using laravel console command.

Preparing database backup for application is very useful to keep application safe in case of any data loss, application crash, etc. Admin can recover the application data from backup. This process also keep users, visitors to stay with application for longer.

In this tutorial we will create a laravel custom command which generates database backup (Complete database structure including data as well) and save inside any folder. And this backup process will run into an automated process inside application.

Learn More –

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

$ composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

$ php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Data Backup Command

We will create a command file inside laravel application. Open project into terminal and run this command into it.

$ php artisan make:command DatabaseBackUp

Command file DatabaseBackUp.php will be created inside /app/Console/Commands folder.

Open DatabaseBackUp.php and write this code into it.

<?php

namespace App\Console\Commands;

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

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 = 'Command description';

    /**
     * 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') . ".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);
    }
}

Code Explanation

Here,

Command name

protected $signature = 'database:backup';

Backup filename

$filename = "backup-" . Carbon::now()->format('Y-m-d') . ".gz";

Above code is to provide the filename of backup file.

Next,

$command = "mysqldump --user=" . env('DB_USERNAME') . " --password=" . env('DB_PASSWORD') . " --host=" . env('DB_HOST') . " " . env('DB_DATABASE') . "  | gzip > " . storage_path() . "/app/backup/" . $filename;

This is the main command which takes the database backup and save into application folder path. This is shell command which usually used direct inside terminal and take backups and all.

env() function returns the name of username, password, host, database name.

exec($command, $output, $returnVar);

exec() It is a PHP function which run shell command.

Register Command as Task Scheduler (Cron)

Next,

To register Cron jobs go to /app/Console folder and find a file called Kernel.php inside it. We need to register our created cron command here with any time when we want to trigger.

Here, are the list of trigger time (scheduling frequencies) available for task scheduling.

Here is the updated code of Kernel.php file.

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        'App\Console\Commands\DatabaseBackUp'
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')->hourly();
        $schedule->command('database:backup')->daily();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__ . '/Commands');

        require base_path('routes/console.php');
    }
}

Settings command will execute on daily basis.

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

Successfully, we have registered Cron command to Kernel.php

Create Backup Folder

Create a folder with name “backup” inside /storage/app folder. Inside this folder we will store database backup files.

Backup files will be created in format of like – backup-2022-08-03.gz

Test Job Scheduling Task

Open terminal and type this command

$ php artisan database:backup

When it executes the command will create a database backup file inside this folder – /storage/app/backup

You will get a file inside above folder in which you can find the database backup what you have created.

Now, let’s set it as on permanent basis by using crontab console command.

Settings Cron Task inside Crontab

Open terminal and type the command

$ crontab -l

This command will list all crons that you have added.

Now, To add new cron tasks, again back to terminal and type the command

$ crontab -e

It will open an interface to your terminal to register or add new tasks. So let’s add

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

  • * * * * * Trigger Time, It indicates our task will run every minute
  • /path-to-your-project This is path of laravel application project
  • php artisan database:backup Command to run.

We hope this article helped you to learn about Laravel 9 Daily Weekly Monthly Automatic Database Backup in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5