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

How to setup Amazon Kinesis Data Stream with Amazon Pinpoint (Part 3)?

In this article, we will discuss "How to setup Amazon Kinesis Data Stream with Amazon Pinpoint (Part 3)?". This article is the third part of our Amazon Pinpoint Series. For better understanding, I recommend to readout the previous article. How to Setup AWS Pinpoint (Part 1) How to Setup AWS Pinpoint SMS Two-Way Communication (Part 2)? Streaming Amazon Pinpoint events to Kinesis In Amazon Pinpoint, when we send a transactional SMS or email message then an event will occur as per the action performed. In a simple way, Amazon Pinpoint sends information about events to Amazon Kinesis. Which, we read and process as per our requirement. We are talking about the SMS so we read the stream data to fetch the delivery reports of our SMSs. There are two types of streams given by the Amazon Kinesis such as Data Firehose, and Data Streams. Amazon Pinpoint can also stream data to Kinesis Data Streams, which ingests and stores multiple data streams for processing by analytics applications. F...

Difference between Kinesis Data Stream and Kinesis Firehose

In this article, we will discuss "Difference between Kinesis Data Stream and Kinesis Firehose" . Today, I will explain the difference between Kinesis Data Stream and Kinesis Firehose . AWS constantly offering the new features and functionality. Kinesis is known as highly available communication channel to stream messages between data producers and data consumers. Data Producers: Source of data such as system or web log data, social network data, financial data, mobile app data, telemetry from connected IoT devices, or etc. Data Consumers: Data processing and storage applications such as Amazon Simple Storage Service (S3), Apache Hadoop, Apache Storm, ElasticSearch, or etc. It is important to understand Kinesis first. Amazon Kinesis is a significant feature in AWS for easy collection, processing, and analysis of video and data streams in real-time environments. AWS Kinesis helps in real-time data ingestion with support for data such as video, audio, IoT telemetry data, appl...

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...