Injecting extra data in the payload of queued jobs in Laravel
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.
What are your thoughts on "Injecting extra data in the payload of queued jobs in Laravel"?