I am using the laravel-data from Spatie package. I have a DTO, and I want to pass it to a job. The DTO has 3 instances of 'UploadedFile', but when passing it, it errors Serialization of 'Illuminate\Http\UploadedFile' is not allowed. Even when excluding the files from the DTO, it still gives this error. How can I fix this, or is my approach wrong?
#Passing a DTO to job, UploadedFile not serializable
15 messages · Page 1 of 1 (latest)
Your approach is wrong. Like the error says, uploaded file instances can’t be passed to jobs, no matter how you try passing them.
You’ll need to save the files first.
Thanks @calm stone. The thing is that the job takes a RegistrationDto, so we can, inside of the job, easily use the properties of this DTO.
Should we avoid passing the DTO directly to the job? I've tried to convert the files to base64, which works fine (inside of the controller). But, when then passing the DTO / excluding these file fields from it, it still gives the error.
The issue is, you can’t pass uploaded files to jobs. So you need to come up with an alternative approach to doing what you’re doing. The reason being, an uploaded file is temporary. If you push a job on the queue, then there’s no guarantee that file is still going to exist when the worker picks up the job.
I see.
So should we get rid of the Dto class as the job parameter? And manually add every property of the Dto to separate parameters?
So, In the controller:
Convert all files to base 64
Pass the base 64s to the job
Pass the other data from the Dto to the job, but not as a Dto instance
I wouldn’t convert the files to Base64-encoded strings. They’re going to be massive and not something you want serialising in your job payloads at all. Some queue drivers even have limits on what size a job payload can be, so you’ll most likely find you’ll exceed them.
Store the files to disk. Then pass the paths to the job. The job can retrieve the files from disk when the worker picks it up.
Similarly to how a full Eloquent model isn’t stored in a job; just it’s ID. The job then retrieves the full model from the database when it’s proceeded by a queue worker.
Alright, makes sense.
And for the DTO to the job? Since the object still contains 3 UploadedFile instances now, so it will error (even though I will handle the file upload inside of the job by passing the file path). The DTO is validating the request from the API as well.
Something you’ll need to work out.
You need to handle the file uploads before the job is dispatched; not during.