Skip to main content

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') . "

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 :)

Comments

Popular posts from this blog

Laravel Logging Guzzle Requests in File

In this article, we will discuss “Laravel Logging Guzzle Requests in File”. In the multiple scenarios, we have to use third-party API’s in our project and test those API using postman or any other tool. But also required to maintain a log for each request, such as what we send (request)? and what we receive (response)? Today, […] Read out the full post at here

How to Use SSH with AWS EC2 Instance?

In this article, we will discuss "How to Use SSH with AWS EC2 Instance?" . As I already explain the setup of EC2 Instance and the use of an Elastic IP in my previous article. Today, we will learn how to connect an EC2 instance using SSH. If still, you have not read my previous articles then I recommend checking them once for a better understanding. Prerequisites A running EC2 Instance . Elastic IP (Optional for this article) ".pem" file, which is downloaded when setup the EC2 Instance. If not having the ".pem" file, then you have to create new key/value pairs. Connect via Terminal or WSL(Window Subsystem for Linux) Open your terminal and go to the directory where you downloaded your ".pem" file. Use the following command to connect with the server. ssh -i "****.pem" username@<publicDNS> or <IP Address> The same terminal command can be used in the windows Linux terminal. I'm using ubuntu on my windows machine...

How to Setup and Install Next.js App?

In this article, we will discuss "How to Setup and Install Next.js App" from scratch. What is React.js and Next.js? "React.js" is a JavaScript library for building user interfaces (elements that users see and interacting on-screen). Basically, React provide us some helpful functions to build UI, and leaves it on us where to use those functions in the application. "Next.js" is a React framework. It is maintained by "Vercel" . Next.js features to solve common application requirements such as routing, data fetching, integrations - all while improving the developer and end-user experience. Why we use Next.js ? Next.js comes with the some additional features to solve come application requirements such as: We can build SSG (Static Site Generation), SSR (Server-Side Rendering) and SPA (Single Page Application) apps. Hot code Reloading: Reload the page when it detects any change saved. Routing: No need to configure any route. Files put in the pages fol...