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 app’s databases somewhere for both save keeping the 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.
The outline of my solution is as follows. There’s an artisan command which handles the backup, that 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.
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.
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, we also pass it other details (line 23-29).
Then in 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 setup 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, that’s the data. You can extend this feature to do more, like attach the .sql file to an email or upload it to dropbox or where ever and so on.
That’s all from me, it’s been Adi - more about me at Simplest Web.