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 24


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 *

    How to use the same Guard name in WEB and API Using Laravel Spatie Permission

    kizinho

    Published

    on

    NEWS: How to use the same Guard name in WEB and API Using Laravel Spatie Permission [New  Developer] » Naijacrawl
    Photo: Naijacrawl
    Hi, Folks will show how to use the same guard name on your Laravel application using Laravel Spatie Permission without creating multiple guards for your web and API when building your real projects.Spatie Permission comes with guard name it is used to authenticate user role and permission in your laravel app. But what if you have Role and Permission with Guard Name Web, it means only web can use this permission or role, when you want to use it for API to Authorize...
    Continue Reading

    Laravel 6.0 - 6.4 - how to fix str_slug and str_limit with any other helpers function

    kizinho

    Published

    on

    NEWS: Laravel 6.0 - 6.4 - how to fix str_slug and str_limit with any other helpers function [New  Developer] » Naijacrawl
    Photo: Naijacrawl
    Hi folks, since laravel 6.0 removed many things like make Auth and Helpers functions. Before you can use them you need to install their packages.You can use helper function like str_slug, which is used to create a slug and str_limit, which is used to set a limit of a string. Today will you how you can make use of it by just installing a package for helper function composer require laravel/helpers That's all you need and start using the helper functions like you a...
    Continue Reading

    Laravel 9.18.0 New Features Detailed

    kizinho

    Published

    on

    DEVELOPER PROGRAMMING: Laravel 9.18.0 New Features Detailed [New  Developer Programming] » Naijacrawl
    Photo: Naijacrawl
    Laravel 9.18.0 comes with a new feature that you will love to upgrade and use, the new features come with 4 main features shipped.Rule objectsQuery timeAttachable objects Nested eager load syntaxRule objects rules that make it simpler to define custom validation rules using simple, single method invokable objects. Very similar API to Closure rules.Query timeintroduced a new method that invokes a closure if cumulative time you spend querying the database during a req...
    Continue Reading

    Latest


    Download Naijacrawl App today

    Fastest way to read on the go

    Download the Naijacrawl App.