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.