Loading relationships inside a queued job

Do it the Laravel way

Joel Clermont
Joel Clermont
2024-03-06

When queuing a Laravel job or notification, any data passed in is serialized so that it can be persisted and later used when the job is run or the notification is sent.

If the data is an Eloquent model, Laravel is smart enough to even serialize any loaded relationships for us automatically.

But for performance reasons, if you're serializing an array or collection of models, relationships are not included. So you'll need to manually load any relations within your job.

Laravel makes eager loading relationships very easy if you're using an EloquentCollection, but if it's a regular Collection or a plain PHP array, you would need to eager load it yourself. Or do you?

An EloquentCollection extends the base Collection, and it's trivial to convert an array to a Collection with the collect() helper method, so we can do something like this:

// app/Notifications/SendReminder.php

public function toMail(): Message
{
    // assuming $this->tasks is an array of Task models
    $tasks = (new EloquentCollection($this->tasks))->load([
        'assignees',
        'tags',
    ]);

    // ... rest of notification logic omitted
}

Here to help,

Joel

P.S. Do you wish you had someone to lean on when you get stuck? Help is a click away.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.