Step-by-Step Guide: Creating a Laravel Database and Files Backup Script Without Using a Package

ArjunAmrutiya
3 min readMar 25, 2024

Introduction:
In any web application, ensuring the safety and integrity of your data is paramount. Having a reliable backup mechanism in place is crucial for safeguarding against data loss. In Laravel, there are several packages available for database and file backups, but sometimes you may prefer to roll your own solution for better customization and control. In this tutorial, we’ll walk through the process of creating a Laravel database and files backup script from scratch, without relying on external packages.

Step 1: Setting Up the Environment
Before diving into coding, ensure you have a Laravel project set up. If you haven’t already, install Laravel using Composer by running the following command:

composer create-project --prefer-dist laravel/laravel your-project-name

Navigate to your project directory and configure your database connection details in the .env file.

Step 2: Creating the Backup Command
In Laravel, artisan commands are an excellent way to encapsulate tasks like backup operations. Let’s create a custom artisan command for our backup script. Run the following command to generate a new command:

php artisan make:command BackupCommand

This will create a new file BackupCommand.php inside the app/Console/Commands directory.

Step 3: Implementing the Backup Logic
Open BackupCommand.php and add the following code to define the command signature and description:

// app/Console/Commands/BackupCommand.php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class BackupCommand extends Command
{
protected $signature = 'backup:run';
protected $description = 'Backup database and files';

public function handle()
{
// Your backup logic goes here
}
}

Step 4: Implementing Database Backup
To backup the database, you can use Laravel’s built-in
mysqldump command (assuming you're using MySQL). Inside the handle() method, add the following code:

// app/Console/Commands/BackupCommand.php

use Illuminate\Support\Facades\DB;

public function handle()
{
$backupPath = storage_path('backups');
$dbName = env('DB_DATABASE');
$backupFile = "{$backupPath}/{$dbName}-" . date('Y-m-d-His') . '.sql';

if (!is_dir($backupPath)) {
mkdir($backupPath, 0755, true);
}

exec("mysqldump -u ".env('DB_USERNAME')." -p".env('DB_PASSWORD')." $dbName > $backupFile");

$this->info('Database backup completed successfully!');
}

Step 5: Implementing File Backup
For file backup, you can use Laravel’s Storage facade. Modify the handle() method to include file backup logic:

// app/Console/Commands/BackupCommand.php

use Illuminate\Support\Facades\Storage;

public function handle()
{
// Database backup logic

$filesBackupPath = storage_path('app/backups');
$timestamp = date('Y-m-d-His');
$zipFileName = "files_backup_{$timestamp}.zip";

if (!file_exists($filesBackupPath)) {
mkdir($filesBackupPath, 0755, true);
}

$files = Storage::allFiles('/');
$zip = new \ZipArchive();
$zip->open($filesBackupPath . '/' . $zipFileName, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);

foreach ($files as $file) {
$zip->addFile(storage_path('app/' . $file), $file);
}

$zip->close();

$this->info('Files backup completed successfully!');
}

Step 6: Running the Backup Command
Now that we’ve implemented the backup logic, you can run the backup command using Artisan:

php artisan backup:run

This will create a database backup and a zip archive containing all files in the storage directory.

Congratulations! You’ve successfully created a custom Laravel database and files backup script without relying on external packages.

Feel free to enhance this script further by adding features like rotation, email notifications, or cloud storage integration to suit your specific requirements. Happy coding!

Go forth and get more out of your content. Go forth and conquer Medium! (and while you’re at it, follow me on Medium! and feel free to Subscribe)

Found this post useful? Kindly tap the 👏 button below! :)

🌟 Enjoy my blogging content? Support my work by buying me a virtual coffee on BuyMeACoffee! Your contributions help fuel insightful tech articles. Join hands in making coding more accessible and exciting for all. https://www.buymeacoffee.com/arjunamrutiya🚀

--

--

ArjunAmrutiya

👋 Hey there! I'm Arjun Amrutiya, a passionate web developer and blogger who loves all things PHP, Laravel and Vue.js. Welcome to my Medium account!