2

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.

Lordwhizy
  • 143
  • 2
  • 10

2 Answers2

5

Simply call the runningInConsole() method :

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

or with the App facade:

if (\App::runningInConsole()) {

to check if execution is happening via CLI.

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
Leo
  • 7,274
  • 5
  • 26
  • 48
0

I have 2 solutions for this. Both work in Laravel 9.

First one

Larvel registers \Illuminate\Queue\CallQueuedHandler 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(\Illuminate\Queue\CallQueuedHandler::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.

jivanrij
  • 157
  • 2
  • 12