I have a custom command for taking backups of my laravel website and I want to make its frequency dynamic, how to achieve that??
My command takes two optional options –only-files and –only-db.
These options and the its frequency based on user preference.
my custom command:
<?php
namespace AppConsoleCommands;
use AppModelsScheduledBackup;
use IlluminateConsoleCommand;
use IlluminateConsoleSchedulingSchedule;
class BackupWebsite extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'BackupWebsite:run';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Backup db and files of the website';
/**
* Execute the console command.
*/
public function handle()
{
$scheduleBackup = self::scheduledBackups();
if($scheduleBackup){
$this->call('backup:run', [
'--only-files' => $scheduleBackup['onlyFiles'],
'--only-db' => $scheduleBackup['onlyDb'],
]);
}
}
function scheduledBackups(){
$scheduleBackup = ScheduledBackup::first();
$files = $scheduleBackup->files;
$database = $scheduleBackup->database;
$repetition = $scheduleBackup->repetition;
if($scheduleBackup->is_active){
if($files && $database){
return ['onlyFiles' => false, 'onlyDb' => false, 'repetition' => $repetition];
}elseif($files){
return ['onlyFiles' => true, 'onlyDb' => false, 'repetition' => $repetition];
}elseif($database){
return ['onlyFiles' => false, 'onlyDb' => true, 'repetition' => $repetition];
}
}
return false;
}
}
this is my routesconsole.php
// I wanna make "daily()" dynamic. Its value stored in db model "ScheduledBackup" column "repetition"
Schedule::command(BackupWebsite::class)->daily()
I did it before in laravel 9 like this:
protected function schedule(Schedule $schedule)
{
$scheduleBackup = self::scheduledBackups();
if($scheduleBackup){
$schedule->command($scheduleBackup['cmd'])->{$scheduleBackup['repetition']}();
}
}