DEV Community

Cover image for Laravel queues: Skip job if no longer required
Sergio Peris
Sergio Peris

Posted on • Originally published at sertxu.dev

Laravel queues: Skip job if no longer required

While working on a Laravel project, we might dispatch a job to a queue.
But what if the job is no longer required when the Laravel queue worker is ready to process it?

For example, a user might cancel a subscription, and we no longer need to send a reminder email.
In this case, we can skip the job if it's no longer required.

To achieve this, we can use the Skip middleware in the job class.

...
use Illuminate\Queue\Middleware\Skip;

class SendReminderEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     */
    public function __construct(private readonly User $user) {}

    /**
     * Get the middleware the job should pass through.
     */
    public function middleware(): array
    {
        return [
            Skip::when(fn () => $this->user->subscription->isCancelled()),
        ];
    }

    /**
     * Handle the job.
     */
    public function handle(): void
    {
        $this->user->sendReminderEmail();
    }
}
Enter fullscreen mode Exit fullscreen mode

As shown in the example above, we can use the Skip middleware to skip the job if the user's subscription is cancelled.

This way, we can avoid processing unnecessary jobs and save resources.

Top comments (0)