Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

Injecting extra data in the payload of queued jobs in Laravel

Original – by Freek Van der Herten – 2 minute read

I'm proud to announce yet another package by our team: spatie/laravel-interacts-with-payload. This one, which was inspired by a blog post by James Brooks, can inject data in all your jobs with just one line of code.

In this video, you'll see the package in action, I explain the internals and the tests. If you prefer reading, continue below the video.

How you can inject things into every job of your app

Imagine that you want to have the user who initiated the queued job available in every queued job. Also, assume that your app has tens or hundreds of jobs you don't want to update manually.

Using this package, this is how you would solve that. Just use AllJobs::add to add things to all jobs.

// typically in the boot method of a service provider

use Spatie\InteractsWithPayload\Facades\AllJobs;

AllJobs::add('user', fn() => auth()->user());

To retrieve the user in your job, you can call getFromPayload, which is available through the InteractsWithPayload trait.

use Illuminate\Contracts\Queue\ShouldQueue;
use Spatie\InteractsWithPayload\Concerns\InteractsWithPayload;

class YourJob implements ShouldQueue
    use InteractsWithPayload;  
    public function handle()
        // instance of User model or `null`
        $user = $this->getFromPayload('user');

If you want to know how the internals of this package work, watch the video linked above or read the code in the repo on GitHub.

Stay up to date with all things Laravel, PHP, and JavaScript.

Follow me on Twitter. I regularly tweet out programming tips, and what I myself have learned in ongoing projects.

Every month I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.


What are your thoughts on "Injecting extra data in the payload of queued jobs in Laravel"?

Comments powered by Laravel Comments
Want to join the conversation? Log in or create an account to post a comment.