Copied!
Laravel
Step-by-Step Guide to Setting Up Automated Database Backups in Laravel
Subheading.jpg
Shahroz Javed
May 18, 2024 . 37 views

Table Of Contents

Introduction:

Welcome to our tutorial! Today, In this guide, we’ll walk you through the process of creating a simple yet effective database backup system in Laravel using a custom controller and route. Ensuring that your database is regularly backed up is crucial for maintaining data integrity and recovering from unforeseen events.

Steps:

1- Create Controller:

php artisan make:controller DBBackupController
          

2- Add mysql path in environment variable

Adjust the path according to your xampp mysql\bin path

D:\xampp7.4.30\mysql\bin
          

3- Writting DB backup logic

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DBBackupController extends Controller
{
    public function dbBackupSql()
    {
        $path = public_path('backup');
        $filename = $path . '/' . "backup-" . now()->format('Y-m-d-H-i-s') . ".sql";

        $username = env('DB_USERNAME');
        $password = env('DB_PASSWORD');
        $host = env('DB_HOST');
        $database = env('DB_DATABASE');

        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }

        $command = "mysqldump --user=" . $username . " --password=" . $password . " --host=" . $host . " " . $database . " > "  . $filename;

        $returnVar = NULL;
        $output  = NULL;

        exec($command, $output, $returnVar);

        return response()->download($filename);
    }
}

          

4- Define the Route:

Route::get('db/backup/sql', [DBBackupController::class, 'dbBackupSql'])->name('db.backup.sql');
          

5- Configure Environment Variables:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password
          

6- Test functionality:

http://your-app-url/db/backup/sql
          

Conclusion:

That's it! You have successfully set up the database backup functionality in your Laravel app.

13 Shares

Related Posts