skip to Main Content

I applied a global scope to my models via a trait, but I don’t want the global scope applied when the model is called/processed from my Redis queue.

How do I detect if the current instance is a queue process? just like we have this

if (App::environment('local')) {
    // The environment is local
}

to detect if the app is running in local or production.

2

Answers


  1. Simply call the runningInConsole() method :

    if (app()->runningInConsole()) {
    

    or with the App facade:

    if (App::runningInConsole()) {
    

    to check if execution is happening via CLI.

    Login or Signup to reply.
  2. I have 2 solutions for this. Both work in Laravel 9.

    First one

    Larvel registers IlluminateQueueCallQueuedHandler in the service container if the app is running in the queue, it does not register that class when running in the console or with a web request. So the following check works and distinguishes between the queue and running on the console.

    // true when code is in the queue
    app()->resolved(IlluminateQueueCallQueuedHandler::class);
    

    Second one

    When Laravel starts a Queue Job there is an event with a callback you can use to attach some currently-running-in-queue flag in the service container.

    // Within the boot method of a service provider
    App::bind('processing-job', function ($app) {
        return false;
    });
    Queue::before(function (JobProcessing $event) {
        App::bind('processing-job', function ($app) {
            return true;
        });
    });
    

    Then you can run a check anywhere like this:

    App::get('processing-job');
    

    Note

    When running tests, and env var QUEUE_CONNECTION is set to sync the test will think you are in a queued process. This is because when working in sync both your test and the job live within the same instance.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search