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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay