diogoazevedos's avatar

Queue model not found

Hi guys,

How can I deal with ModelNotFoundException in a Queued Job?

0 likes
2 replies
magnetas's avatar
Level 8

Hi there. Here's what I came up with after asking the same question in SO and getting some hints: I wrote my own trait that basically decorates the one you originally use. So instead of 'use SerializesModels' you write 'use SerializesNullableModels' in your jobs and you get null instead of missing object but the exception does not mess anything up. Here's the trait:

<?php

namespace App\Jobs;

use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Database\ModelIdentifier;
use Illuminate\Database\Eloquent\ModelNotFoundException;

trait SerializesNullableModels
{
    use SerializesModels {
        SerializesModels::getRestoredPropertyValue as parentGetRestoredPropertyValue;
    }

    protected function getRestoredPropertyValue($value)
    {
        try
        {
            return $this->parentGetRestoredPropertyValue($value);
        }
        catch (ModelNotFoundException $e)
        {
            return null;
        }
    }
}
3 likes

Please or to participate in this conversation.