How to Set up Automatic DB Backup in Laravel [Snippet]

DZone 's Guide to

How to Set up Automatic DB Backup in Laravel [Snippet]

Let's see how to set up automatic database backup in Laravel.

· Database Zone ·
Free Resource

Image title

Automatic DB backup in Laravel

Hi all, this is Adi again with a Laravel-related article. This time in a shorter format. As Laravel developers, we need a way to back up our apps' databases somewhere for both saving/keeping data and for analysis. I want to share with you a simple solution that I have devised for some of my smaller projects. I have tested this method only on MySQL DB and on a VPS, but I think it’s pretty much the same for any database.

You may also like:  Website Backups in 7 Simple Steps


The outline of my solution is as follows. There’s an artisan command that handles the backup and runs periodically using a cron. This command makes use of the mysqldump tool that comes with all MySQL installations. mysqldump dumps the given DB into a .sql and we can control where it is dumped. And that’s how my solution works. Now let’s see some code.

The Code

First off, create an Artisan command like so: php artisan make:command BackupDatabase. This should create a class with the name you mentioned in the command and should also have some default scaffolding for the command.

DB Backup command

Let me explain what the above code does. Within the constructor, we prepare the name of the file (line 20), then we check if there’s a folder named backups within the storage folder. If not, we create it (line 21). Then, we instantiate a process with the command that we want to be executed, and we also pass it to other details (line 23-29).

Then, the handle method runs the process and logs the output to the application logs. This handle method is executed after the constructor by Laravel itself, so you don’t have to invoke it from anywhere.

And finally, you need to set up cron. You have 2 options here; either you can call Laravel’s schedule:run command or call your backup command directly.


This is a pretty simple and neat solution for backing up your most valuable asset: the data. You can extend this feature to do more, like attach the .sql file to an email or upload it to Dropbox or wherever and so on.

That’s all from me, Adi — more about me at Simplest Web.

Related resources

Further Reading

Database Backup: A Conversation With an Expert

How to Backup and Restore MySQL Database Files

artisan command ,automatic db backup ,database ,laravel 5 ,laravel developers ,laravel tutorial ,mysql ,php ,tutorial

Published at DZone with permission of Adi Sk . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}