Written By

Helper to detect if Laravel is running a job

Helper to detect if Laravel is running a job

Create a service class

<?php

namespace App\Services;

class AppState
{
    public bool $isProcessingJob = false;
}

Add these methods to any ServiceProvider

use Illuminate\Queue\Events\JobProcessed;
use Illuminate\Queue\Events\JobProcessing;
use App\Services\AppState;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Queue;


private function registerAppStateService(): void
{
    $this->app->singleton(AppState::class, fn (): AppState => new AppState());
}

private function detectQueueState(): void
{
        Queue::before(function (JobProcessing $event): void {
            app(AppState::class)->isProcessingJob = true;
        });

        Queue::after(function (JobProcessed $event): void {
            app(AppState::class)->isProcessingJob = false;
        });

        App::macro('isProcessingJob', function (): bool {
            return app(AppState::class)->isProcessingJob;
        });
}

Add them to the boot() and register() methods of the same service provider, to ensure they get registered.


public function register(): void
{
    $this->registerAppStateService();
}


public function boot(): void
{
    $this->detectQueueState();
}

Now you can use it anywhere in your Laravel app to evaluate if the code is running inside a job.

use Illuminate\Support\Facades\App;


if (App::isProcessingJob()) {
    //running a job
}

//or 
if (app()->isProcessingJob()) {
    //running a job
}

Other use case for the AppState service class

Conditional Soft Deleting Scope

Related Laravel documentation

Comments (0)

loading comments