Connect with us

Laravel Backup Your Mysql Database With Delete Old Files and Notification Functionalities

kizinho

Published

on

Follow
DEVELOPER PROGRAMMING: Laravel Backup Your Mysql Database With Delete Old Files and Notification Functionalities [New  Developer Programming] » Naijacrawl
Photo: Naijacrawl

site

Hi, folks am happy to share this with you as you already know how backing up your database is very important to avoid data loss, if you are looking for a way to backup your database using Laravel version 5 to 8, you are at the right place. At the end of this article I will provide the source code, GitHub repo and youtube video to make sure I put you through without facing any challenges, and if you face any don't forget to reach me via the comment box.

How you will learn

  1. How to backup your database
  2. Delete old files to free up space
  3. send notification

following this tutorial, you will first install a fresh laravel app or use your old laravel app.

if you are coming from using the fresh laravel app do this, if you are not skip.

Install via Laravel global command

laravel new database_backup --git

or install via composer command

composer create-project laravel/laravel database_backup

The next step is for fresh installation and old projects


go to app/config.php to setup data that we will use to access the database for the backup

  'db_username' => env('DB_USERNAME'),
  'db_password' => env('DB_PASSWORD'),
  'db_host' => env('DB_HOST'),
  'db_database' => env('DB_DATABASE'),

create backup database command using

 php artisan make:command BackupDatabase  

A new file will be created under this folder app\Console\Commands\BackupDatabase.php, open it and paste this code snippet

namespace App\Console\Commands;


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


class BackupDatabase extends Command {


    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    //call it with php artisan backup:db to run the code
    protected $signature = 'backup:db';


    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct() {
        parent::__construct();
        //calling it from the config we added before
        $this->host = config('app.db_host');
        $this->user = config('app.db_username');
        $this->pass = config('app.db_password');
        $this->dbname = config('app.db_database');
    }


    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle() {
        //code that will handle the backup
        try {
            //path directory to store the file
            $storePath = storage_path() . '/app/backup';
            //filename , name of the file 
            $filename = 'backup' . Carbon::now()->format('Y_m-d') . '.sql';


            //check if the path directory exist and skip if not create it before procceeding
            if (!is_dir(dirname($storePath))) {
                //we create fuction to create the path
                static::createPathDiretory($storePath);
            }
            //handling the backup
            $command = "mysqldump --user=" . $this->user . " --password=" . $this->pass . " --host=" . $this->host . " " . $this->dbname . " > " . $storePath . $filename;
            $returnVar = null;
            $output = null;
            exec($command, $output, $returnVar);


            //adding function to delete old files after successfully backup of new files 
            $time = 345600; //time is in seconds eg 4 days = 345600 , delete file after 4 days
            //function to handle delete file
            static::deleteOldFiles($storePath, $time);
            //send notification after successful backup
            //send notification to email using your already mailling functions
        } catch (Exception $ex) {
            //backup fails 
            //send notification to email using your already mailling functions
        }
    }


    public static function createPathDiretory($path_dir, $abs = true) {


        if (!is_dir($path_dir)) {
            //create the path with permission to read and write
            mkdir($path_dir, 0777, true);
        }
        return ($abs ? $path_dir : $path_dir);
    }


    public static function deleteOldFiles($storePath, $time) {
        //loop into the directory and put all the files in foreach to check
        foreach (glob($storePath . "*") as $file) {
            //check the file that its time is more than 4 days depends on your own time
            if (time() - filectime($file) > $time) {
                unlink($file);
            }
        }
    }


}

to test the code on your live server use php artisan backup:db 

Next step, we need to add it for automation to avoid accessing it always from terminal

locate app\Console\Kernel.php

use App\Console\Commands\BackupDatabase;

  protected $commands = [
        //adding the backup to laravel schedule
        BackupDatabase::class
    ];

  protected function schedule(Schedule $schedule)
    {
        //depends on your need 
         $schedule->command('backup:db')->daily();
         //go to your cpanel, cron job and add this command//         /usr/local/bin/php /home/hostusername/root folder/artisan schedule:run >> /dev/null 2>&1
    }

The last step go to your cpanel, cron job and add this command

/usr/local/bin/php /home/hostusername/root folder/artisan schedule:run >> /dev/null 2>&1

Congratulations you have successfully learned how to backup your database, find this article and resources helpful kindly share and comment, it will encourage me to write more on laravel and other languages.

Github link: Backupdatabase

Click Here To Comment

Download File 91.35 Kb 15


site


kizinho

Adike Kizito is a top-rated software developer, blogger, sports, and entertainment lover. He is the CEO of these popular websites Naijacrawl.com and Mp3ager.com. He operates his software developing task through Kizzsoft.com,... Read More

Continue Reading
Click to comment

Be first to comment


    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Laravel 9 Release Date and New Features

    kizinho

    Published

    on

    DEVELOPER PROGRAMMING: Laravel 9 Release Date and New Features [New  Developer Programming] » Naijacrawl
    Photo: Naijacrawl
    Laravel community has updated about the new release of another version of Laravel called laravel 9. With laravel 9 it brings new features that you will love and it will be released earlier next year in 2022 due to some dependencies of Symphony they depend on which will be available by November 2021 and Laravel normally gives 2 months after symphony updates to release a new version of laravel.Let's look at the new features Laravel introduced a new query builder which...
    Continue Reading

    Mastering Laravel MVC (Model View Controller) and Folder Structures

    kizinho

    Published

    on

    DEVELOPER PROGRAMMING: Mastering Laravel MVC (Model View Controller) and Folder Structures [New  Developer Programming] » Naijacrawl
    Photo: Naijacrawl
    Hi, folks, we have successfully created the laravel project in the last class, if you missed it go back and create a new laravel project here.Before going to MVC (Model View Controller) let's serve up the project for development purposes using the following commandphp artisan serve output resultStarting Laravel development server: http://127.0.0.1:8000 incase if you want to serve your project from a different port number, use the following command belowphp artisan...
    Continue Reading

    Laravel 6 and 7 Package for Paystack

    kizinho

    Published

    on

    NEWS: Laravel  6 and  7 Package for Paystack [New  Developer] » Naijacrawl
    Photo: Naijacrawl
    Hi, Folks since the release of laravel version 6 and 7, it is very difficult to easily use Paystack on it due to lack of maintenance but today unicodeveloper of the package have taken his time to release a new update on the package.To use it, you just need to follow the same pattern we normally do and get things working back again.Visit the package URL here
    Continue Reading

    Latest


    Download Naijacrawl App today

    Fastest way to read on the go

    Download the Naijacrawl App.