Eloquent Serializing: Models in Queues
Eloquent Serializing: Models in Queues
Eloquent Serializing: Models in Queues
Tip: Model Serialization in Jobs
When you pass a model to a queued job, Laravel serializes only the identifier. The model is re-fetched when the job runs.
Gotcha: Deleted Models Cause Job Failures
If the model is deleted before the job runs, the job throws ModelNotFoundException.
Tip: SerializesModels Trait
class ProcessPodcast implements ShouldQueue
{
use SerializesModels;
}
Automatically handles model serialization in jobs.
Gotcha: Loaded Relations Are Serialized Too
If you eager load relations before passing to a job, they're serialized. This can bloat the queue payload.
Tip: Pass ID Instead of Model
ProcessPodcast::dispatch($post->id);
More explicit, avoids serialization surprises.
Gotcha: getQueueableRelations()
public function getQueueableRelations(): array
{
return []; // Don't serialize any relations
}
Tip: Use cursor() for Memory-Neutral Iteration
When exporting 100K rows, get() loads everything into memory. cursor() uses yield and keeps memory flat regardless of row count. Perfect for artisan commands.
Tip: whereHas() vs load() — Two Different Things
whereHas() filters the parent query by relationship existence. load() eager-loads relationships AFTER the query. Mixing them up is a common source of logic bugs.
Gotcha: withCount() Adds a Subquery
withCount('comments') runs a correlated subquery on every row. On large tables, this can be slower than a separate query. Profile before relying on it.
Senior Insight
Validation in Eloquent is a layered responsibility. Database constraints catch data integrity violations. Form Requests catch user input errors. Model events catch application-level business rules. I've seen teams rely on only one layer (usually Form Requests) and have inconsistent data when the same model is updated through Artisan commands or API calls. All data writes should pass through the same validation layers, regardless of the entry point.
Source: Laravel Docs (https://laravel.com/docs/eloquent), Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/eloquent)