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
Simply call the
runningInConsole()
method :or with the App facade:
to check if execution is happening via CLI.
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.
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.
Then you can run a check anywhere like this:
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.