Friday, February 8, 2019

Middleware when running Artisan console request

I want a custom piece of middleware to run whenever I run an artisan command. I need to set a few environment variables to be used in the app configuration before the actual command executes.
There is a way around but not sure if the correct one, but works. Just open up the Kernel class and override the bootstrap method. Laravel 5.3, have not tested on other versions, but should work similarly
<?php
namespace App\Console;

use Log;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\Inspire::class,
    ];

    public function bootstrap() {
        parent::bootstrap();
        Log::info("KERNEL COMMAND EXECUTING");
    }

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->call('App\Service\YourService@method')->dailyAt('10:00');

        $schedule->call('App\Service\YourService@method')->everyFiveMinutes();
    }
}
And finally the Kernel is executed by CronJob or Laravel Jobs.
To add Laravel kernel scheduler to CronJob, execute command crontab -e and add below line and save the operation.
* * * * * /usr/local/bin/php /project_location/www/project/artisan schedule:run >> /dev/null 2>&1

No comments:

Post a Comment