What are you looking for?
Search by 3MGC
What are you looking for?
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.
php artisan make:controller DBBackupController
Adjust the path according to your xampp mysql\bin path
D:\xampp7.4.30\mysql\bin
<?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); } }
Route::get('db/backup/sql', [DBBackupController::class, 'dbBackupSql'])->name('db.backup.sql');
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
http://your-app-url/db/backup/sql
That's it! You have successfully set up the database backup functionality in your Laravel app.