La mejor seguridad en cualquier proyecto sea cual sea el lenguaje de programación o framework utilizado es tener copias de seguridad de todo en algún sitio, preferiblemente fuera del servidor de origen por si éste se ve comprometido.
En esta entrada verás lo sencillo que es realizar copias de seguridad en Laravel, tanto de archivos como de bases de datos en los momentos que tú decidas, aunque yo recomiendo realizar las copias de base de datos mínimo 1 vez al día y, dependiendo del tipo de proyecto, ventas de productos, suscripciones etcétera, incluso sería recomendable realizar las copias de seguridad 1 vez cada x horas al día.
La mejor herramienta sin duda para realizar copias de seguridad en Laravel es Spatie Backup, la cual es compatible desde Laravel 5.1.20 y Php 5.5.9. Este fantástico paquete está disponible para MySQL y PostgreSQL a través de mysqldump y pg_dump respectivamente.
En nuestro caso vamos a ver cómo utilizar la última versión de Spatie Backup, la 7, la cual requiere tener instalado PHP 8 o superior, la extensión ZIP y Laravel 8 o superior, con eso tenemos suficiente.
Instalar Spatie Backup
composer require spatie/laravel-backupPublicar archivo de configuración
php artisan vendor:publish --provider="Spatie\Backup\BackupServiceProvider"El archivo de configuración por defecto contiene lo siguiente:
<?php
return [
'backup' => [
/*
* The name of this application. You can use this name to monitor
* the backups.
*/
'name' => env('APP_NAME', 'laravel-backup'),
'source' => [
'files' => [
/*
* The list of directories and files that will be included in the backup.
*/
'include' => [
base_path(),
],
/*
* These directories and files will be excluded from the backup.
*
* Directories used by the backup process will automatically be excluded.
*/
'exclude' => [
base_path('vendor'),
base_path('node_modules'),
],
/*
* Determines if symlinks should be followed.
*/
'follow_links' => false,
/*
* Determines if it should avoid unreadable folders.
*/
'ignore_unreadable_directories' => false,
/*
* This path is used to make directories in resulting zip-file relative
* Set to `null` to include complete absolute path
* Example: base_path()
*/
'relative_path' => null,
],
/*
* The names of the connections to the databases that should be backed up
* MySQL, PostgreSQL, SQLite and Mongo databases are supported.
*
* The content of the database dump may be customized for each connection
* by adding a 'dump' key to the connection settings in config/database.php.
* E.g.
* 'mysql' => [
* ...
* 'dump' => [
* 'excludeTables' => [
* 'table_to_exclude_from_backup',
* 'another_table_to_exclude'
* ]
* ],
* ],
*
* If you are using only InnoDB tables on a MySQL server, you can
* also supply the useSingleTransaction option to avoid table locking.
*
* E.g.
* 'mysql' => [
* ...
* 'dump' => [
* 'useSingleTransaction' => true,
* ],
* ],
*
* For a complete list of available customization options, see https://github.com/spatie/db-dumper
*/
'databases' => [
'mysql',
],
],
/*
* The database dump can be compressed to decrease diskspace usage.
*
* Out of the box Laravel-backup supplies
* Spatie\DbDumper\Compressors\GzipCompressor::class.
*
* You can also create custom compressor. More info on that here:
* https://github.com/spatie/db-dumper#using-compression
*
* If you do not want any compressor at all, set it to null.
*/
'database_dump_compressor' => null,
/*
* The file extension used for the database dump files.
*
* If not specified, the file extension will be .archive for MongoDB and .sql for all other databases
* The file extension should be specified without a leading .
*/
'database_dump_file_extension' => '',
'destination' => [
/*
* The filename prefix used for the backup zip file.
*/
'filename_prefix' => '',
/*
* The disk names on which the backups will be stored.
*/
'disks' => [
'local',
],
],
/*
* The directory where the temporary files will be stored.
*/
'temporary_directory' => storage_path('app/backup-temp'),
/*
* The password to be used for archive encryption.
* Set to `null` to disable encryption.
*/
'password' => env('BACKUP_ARCHIVE_PASSWORD'),
/*
* The encryption algorithm to be used for archive encryption.
* You can set it to `null` or `false` to disable encryption.
*/
'encryption' => \ZipArchive::EM_AES_256,
],
/*
* You can get notified when specific events occur. Out of the box you can use 'mail' and 'slack'.
* For Slack you need to install laravel/slack-notification-channel.
*
* You can also use your own notification classes, just make sure the class is named after one of
* the `Spatie\Backup\Events` classes.
*/
'notifications' => [
'notifications' => [
\Spatie\Backup\Notifications\Notifications\BackupHasFailedNotification::class => ['mail'],
\Spatie\Backup\Notifications\Notifications\UnhealthyBackupWasFoundNotification::class => ['mail'],
\Spatie\Backup\Notifications\Notifications\CleanupHasFailedNotification::class => ['mail'],
\Spatie\Backup\Notifications\Notifications\BackupWasSuccessfulNotification::class => ['mail'],
\Spatie\Backup\Notifications\Notifications\HealthyBackupWasFoundNotification::class => ['mail'],
\Spatie\Backup\Notifications\Notifications\CleanupWasSuccessfulNotification::class => ['mail'],
],
/*
* Here you can specify the notifiable to which the notifications should be sent. The default
* notifiable will use the variables specified in this config file.
*/
'notifiable' => \Spatie\Backup\Notifications\Notifiable::class,
'mail' => [
'to' => '[email protected]',
'from' => [
'address' => env('MAIL_FROM_ADDRESS', '[email protected]'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
],
'slack' => [
'webhook_url' => '',
/*
* If this is set to null the default channel of the webhook will be used.
*/
'channel' => null,
'username' => null,
'icon' => null,
],
],
/*
* Here you can specify which backups should be monitored.
* If a backup does not meet the specified requirements the
* UnHealthyBackupWasFound event will be fired.
*/
'monitor_backups' => [
[
'name' => env('APP_NAME', 'laravel-backup'),
'disks' => ['local'],
'health_checks' => [
\Spatie\Backup\Tasks\Monitor\HealthChecks\MaximumAgeInDays::class => 1,
\Spatie\Backup\Tasks\Monitor\HealthChecks\MaximumStorageInMegabytes::class => 5000,
],
],
/*
[
'name' => 'name of the second app',
'disks' => ['local', 's3'],
'health_checks' => [
\Spatie\Backup\Tasks\Monitor\HealthChecks\MaximumAgeInDays::class => 1,
\Spatie\Backup\Tasks\Monitor\HealthChecks\MaximumStorageInMegabytes::class => 5000,
],
],
*/
],
'cleanup' => [
/*
* The strategy that will be used to cleanup old backups. The default strategy
* will keep all backups for a certain amount of days. After that period only
* a daily backup will be kept. After that period only weekly backups will
* be kept and so on.
*
* No matter how you configure it the default strategy will never
* delete the newest backup.
*/
'strategy' => \Spatie\Backup\Tasks\Cleanup\Strategies\DefaultStrategy::class,
'default_strategy' => [
/*
* The number of days for which backups must be kept.
*/
'keep_all_backups_for_days' => 7,
/*
* The number of days for which daily backups must be kept.
*/
'keep_daily_backups_for_days' => 16,
/*
* The number of weeks for which one weekly backup must be kept.
*/
'keep_weekly_backups_for_weeks' => 8,
/*
* The number of months for which one monthly backup must be kept.
*/
'keep_monthly_backups_for_months' => 4,
/*
* The number of years for which one yearly backup must be kept.
*/
'keep_yearly_backups_for_years' => 2,
/*
* After cleaning up the backups remove the oldest backup until
* this amount of megabytes has been reached.
*/
'delete_oldest_backups_when_using_more_megabytes_than' => 5000,
],
],
];Seleccionar el disco para las copias de seguridad
Por defecto este paquete guarda las copias de seguridad en el disco configurado con local, lo puedes ver en el anterior archivo de configuración. Mi recomendación es utilizar S3 o una alternativa similar para evitar guardar datos tan sensibles en el mismo servidor, ya que sería muy sencillo para los atacantes acceder a esta información.
Crear copias de seguridad diariamente
Una vez tenemos Spatie Backup instalado y configurado, podemos crear un scheduler que haga el trabajo a diario por nosotros desde el Kernel de la consola.
<?php
protected function schedule(Schedule $schedule) {
// genera una copia de seguridad completa, base de datos y archivos cada día a las 09:00
$schedule->command("backup:run")->dailyAt("09:00");
// genera una copia de seguridad de la base de datos cada día a las 09:00
$schedule->command("backup:run --only-db")->dailyAt("09:00");
// genera una copia de seguridad de los archivos cada día a las 09:00
$schedule->command("backup:run --only-files")->dailyAt("09:00");
}Extra, enviar copia de seguridad de base de datos por correo
Una funcionalidad que sin duda me encanta de este paquete es tener la posibilidad de utilizar determinados eventos a través de notificaciones para enviar por correo electrónica las copias de seguridad realizadas.
Si revisas el archivo config/backup.php y la clave notifications => notifications, verás que tenemos una serie de notificaciones ya disponibles para notificar cuando un evento se lleve a cabo.
En nuestro caso, y ya que estamos creando copias de seguridad, el evento que nos interesa es BackupWasSuccessfulNotification. Este evento nos notificará, pero no envía la copia de seguridad por correo, pero es muy sencillo hacerlo, el siguiente código realiza el proceso.
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Facades\Storage;
class BackupWasSuccessfulNotification extends \Spatie\Backup\Notifications\Notifications\BackupWasSuccessfulNotification
{
use Queueable;
/**
* @throws FileNotFoundException
*/
public function toMail(): MailMessage {
// eliminamos el directorio de backups local para no dejar archivos innecesarios
Storage::disk("local")->deleteDirectory($this->applicationName());
// obtenemos el último backup de S3
$s3Backup = Storage::disk($this->diskName())->get($this->event->backupDestination->newestBackup()->path());
// copiamos el backup de S3 a nuestro servidor para enviar por correo electrónico
Storage::disk('local')->put($this->event->backupDestination->newestBackup()->path(), $s3Backup);
// generamos la notificación adjuntando el backup del servidor
$mailMessage = (new MailMessage())
->from(config('backup.notifications.mail.from.address', config('mail.from.address')), config('backup.notifications.mail.from.name', config('mail.from.name')))
->subject(trans('backup::notifications.backup_successful_subject', ['application_name' => $this->applicationName()]))
->line(trans('backup::notifications.backup_successful_body', ['application_name' => $this->applicationName(), 'disk_name' => $this->diskName()]))
->attach(Storage::disk("local")->path($this->event->backupDestination->newestBackup()->path()), [
'as' => sprintf("%s.zip", now()->format("d-m-Y-H-i-s")),
'mime' => 'application/zip',
]);
$this->backupDestinationProperties()->each(function ($value, $name) use ($mailMessage) {
$mailMessage->line("{$name}: $value");
});
return $mailMessage;
}
}Para que Spatie Backup utilice nuestra notificación, recuerda reemplazar la notificación por la nuestra en el archivo de configuración config/backup.php.
Proteger con contraseñas nuestros .zip
Por si fuera poco, este paquete también nos permite proteger con contraseñas nuestros archivos .zip. Para ello, simplemente añade la variable de entorno BACKUP_ARCHIVE_PASSWORD a tu .env. Con este ajuste, todos los .zip generados por este paquete estarán protegidos por contraseña.
Espero que te haya gustado esta entrada, si quieres ver más temas interesantes y relacionados con la seguridad en Laravel no te pierdas este curso.
Curso Laravel 12
Completo 2026
El único curso 100% actualizado que incluye Laravel 12, Livewire 3, Vue 3, React 19 e Inertia 2. Aprende con proyectos reales y las últimas funcionalidades.
star Incluido en cualquier suscripción