We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Today, I want to talk about a lesser known feature in Laravel which is console routes.
Often, you have console commands which need to run one after the other (especially if you don't want to create one big command).
By using console routes, you can group commands together into a new command.
Let's have a look at an example. I'm using the Spatie laravel-backup module in almost every site I setup.
At night, there are three commands I always want to run, one after the other.
To do this, open the file routes/console.php
and add the following to it:
use Illuminate\Support\Facades\Artisan;
use Spatie\Backup\Commands\BackupCommand;
use Spatie\Backup\Commands\CleanupCommand;
use Spatie\Backup\Commands\MonitorCommand;
/*
|--------------------------------------------------------------------------
| Console Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of your Closure based console
| commands. Each Closure is bound to a command instance allowing a
| simple approach to interacting with each command's IO methods.
|
*/
Artisan::command('run:nightly', function () {
Artisan::call(BackupCommand::class);
Artisan::call(CleanupCommand::class);
Artisan::call(MonitorCommand::class);
})->describe('Running nightly commands');
This defines a new run:nightly
command in artisan which first run the backup
command, then the cleanup
command and finishes with the monitor
command.
This makes it easier as now I can schedule a single command to be run at a specific time instead of having to define it three times.
In my console/Kernel.php
file, I can now do:
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected function schedule(Schedule $schedule)
{
$schedule->command('run:nightly')->daily()->at('03:15');
}
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
You can read more about it in the Laravel documentation.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.