laravel-5.7laravel-events

Laravel - writing exception for schedule event in model listener


I've a Model Product that fires retrieved event ProductRetrieved and a listener CheckProductValidity that throws an exception depending on the API path (if-else condition).

Also, I've a update query that I have implemented in Console\Kernal.php that runs everyday at 00:00 Hours.

Problem: CheckProductValidity throws an exception for scheduled tasks. How do I make an exception in listener to allow retrieval of model Product data when it is done by scheduler.

Possible solution: Use unsetEventDispatcher and setEventDispatcher but at times this update query may take more than usual time. Also, cron also sends notifications and processes jobs (all depending on Product) so that might cause problems.


Solution

  • Not really a solution but this is how I fixed it.

    // fix to catch if artisan schedule:run has intiated this check;
    $parameters = app('request')->server->get('argv');
    
    $allowed_commands = ['schedule:run', 'migrate:refresh', 'db:seed', 'queue:work'];
    
    if ($parameters[0]==='artisan'
        && in_array($parameters[1], $allowed_commands))
        return true;
    

    In the listener I added this code which would check if the request was a result of artisan command or a route.