in Laravel Jobs

Laravel Delete Model Not Found Jobs

In this post we're going to look into a little laravel feature that allows jobs to automatically be deleted if the models in the job doesn't exist.

Laravel jobs are asynchronous code that can run in the background of your application, they can even be delayed until a further date. Because these jobs are asynchronous there is no guarantee that the models inside your job will be found by the time the job runs.

For example if you have a blog post and you setup a job to publish this to twitter, and by the time the job run the blog post has been deleted then the job will throw a ModelNotFoundException. When Laravel jobs throw an exception they will be marked as failed, retried and moved to the failed jobs table. If the model doesn't exist then everytime the job attempts a retry it will again throw the same ModelNotFoundException causing it to unnecessarily rerun the failed job.

Laravel has a setting you can place on your job to delete the job when it throws the ModelNotFoundException rather than setting it to failed.

In your job class add the public property deleteWhenMissingModels and set it to true.

<?php

class Job implements ShouldQueue
{
    public $deleteWhenMissingModels = true;

    public function handle()
    {

    }
}

This is a very quick tip and can save your queue worker from running unnecessary jobs and save populating the failed jobs table with jobs when can not be retried.

Subscribe To The Weekly Newsletter

Get weekly updates to your email