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.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

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

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay