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)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay