Laravel Daily Automatic Database Backup Example Tutorial

10-Apr-2023

.

Admin

Laravel Daily Automatic Database Backup Example Tutorial

Hello Friend,

Today, I am going to show you how to database backup daily automatically in laravel app. We have to need backup our database automatically daily in laravel application.

In this tutorial will help you step by step to take automatic database backup daily using artisan command in laravel apps.

In this blog, I will teach you laravel daily automatic database backup example.

Step 1 : Run command


In first step, You can navigate to your laravel app directory thenafter run bellow artisan command. This command to create myDbBackup.php file for automatically database backup.

php artisan make:command myDbBackup

Step 2 : Register command in Kernel.php file

In this step, You can register above command file into kernel.php file. So Let's open kernel.php file and make changes in this file.

app/Console/Kernel.php

<?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\myDbBackup'

];

/**

* Define the application's command schedule.

*

* @param \Illuminate\Console\Scheduling\Schedule $schedule

* @return void

*/

protected function schedule(Schedule $schedule)

{

$schedule->command('inspire')->daily();

}

/**

* Register the commands for the application.

*

* @return void

*/

protected function commands()

{

$this->load(__DIR__.'/Commands');

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

}

}

Step 3 : Edit in myDbBackup.php File

In the last step, You can make chnages into myDbBakcup.php file. I am create database backup zip file create into storage/app/backup/ so navigate path in this file.

app/Console/Commands/myDbBackup.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class myDbBackup extends Command

{

/**

* The name and signature of the console command.

*

* @var string

*/

protected $signature = 'command:name';

/**

* 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\Carbon::now()->format('d-m-Y') . ".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);

}

}

It will help you...

#Laravel 7

#Laravel

#Laravel 6