26

Injecting extra data in the payload of queued jobs in Laravel

 3 years ago
source link: https://freek.dev/1960-injecting-extra-data-in-the-payload-of-queued-jobs-in-laravel
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Datadog collects and monitors your PHP app metrics and distributed traces in real-time with application performance monitoring. Decrease downtime and performance issues with Datadog APM by tracing requests across service boundaries and drilling into individual traces end-to-end with flame graphs. Start your 14-day trial for free today.

Injecting extra data in the payload of queued jobs in Laravel

Original – Apr 20th 2021 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 two weeks 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.

Comments #


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK