#development #laravel #php #terminal

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:

 1use Illuminate\Support\Facades\Artisan;
 2use Spatie\Backup\Commands\BackupCommand;
 3use Spatie\Backup\Commands\CleanupCommand;
 4use Spatie\Backup\Commands\MonitorCommand;
 5
 6/*
 7|--------------------------------------------------------------------------
 8| Console Routes
 9|--------------------------------------------------------------------------
10|
11| This file is where you may define all of your Closure based console
12| commands. Each Closure is bound to a command instance allowing a
13| simple approach to interacting with each command's IO methods.
14|
15*/
16
17Artisan::command('run:nightly', function () {
18    Artisan::call(BackupCommand::class);
19    Artisan::call(CleanupCommand::class);
20    Artisan::call(MonitorCommand::class);
21})->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:

 1namespace App\Console;
 2
 3use Illuminate\Console\Scheduling\Schedule;
 4use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
 5
 6class Kernel extends ConsoleKernel
 7{
 8    protected function schedule(Schedule $schedule)
 9    {
10        $schedule->command('run:nightly')->daily()->at('03:15');
11    }
12
13    protected function commands()
14    {
15        $this->load(__DIR__.'/Commands');
16
17        require base_path('routes/console.php');
18    }
19}

You can read more about it in the Laravel documentation.