Laravel Schedule Database Backup

Many times we face the problem that data is lost or database get corrupted. So it’s necessary to keep regular backup of database and it’s tedious to take backup manually. So here is a trick which will take DB backup automatically everyday.
Step 1. Go to App/Console and create new folder “Console”. Now create new file under Console folder and named it “DbBackup.php” and paste below code.
<?php
namespace App\Console\Commands;use Illuminate\Console\Command;
use Carbon\Carbon;class DbBackup extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'db:backup';/**
* The console command description.
*
* @var string
*/
protected $description = 'Create Database Backup';/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$filename = "backup-" . Carbon::now()->format('Y-m-d') . ".gz"; $command = "mysqldump --opt --databases ".env('DB_DATABASE')." -h ".env('DB_HOST')." -u " . env('DB_USERNAME') ." -p'" . env('DB_PASSWORD') . "' | gzip > " . storage_path() . "/app/" . $filename; $returnVar = NULL;
$output = NULL; exec($command, $output, $returnVar);
}
}
Here we have created Laravel scheduler command which will take backup of database in zipped format and place file at “storage/app/backup”. Now we have to schedule this command to run everyday.
Step 2. Edit the “Kernel.php” file at “App/Console” with below code.
<?phpnamespace 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\DbBackup'
]; /**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('db:backup')->daily();
} /**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands'); require base_path('routes/console.php');
}
}
Here we have registered our scheduler command and scheduled to run everyday.