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.
<span class="hljs-comment">// typically in the boot method of a service provider</span>
<p><span class="hljs-keyword">use</span> <span class="hljs-title">Spatie</span><span class="hljs-title">InteractsWithPayload<span class="hljs-title">Facades<span class="hljs-title">AllJobs;</p>
<p>AllJobs::add(<span class="hljs-string">'user'</span>, fn() => auth()->user());
</p>
To retrieve the user in your job, you can call getFromPayload
, which is available through the InteractsWithPayload
trait.
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span><span class="hljs-title">Contracts<span class="hljs-title">Queue<span class="hljs-title">ShouldQueue;
<span class="hljs-keyword">use</span> <span class="hljs-title">Spatie</span><span class="hljs-title">InteractsWithPayload<span class="hljs-title">Concerns<span class="hljs-title">InteractsWithPayload;
<p><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">YourJob</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">ShouldQueue</span>
</span>{
<span class="hljs-keyword">use</span> <span class="hljs-title">InteractsWithPayload</span>;</p>
<pre><code><span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handle</span><span class="hljs-params">()</span>
</span>{
<span class="hljs-comment">// instance of User model or `null`</span>
$user = <span class="hljs-keyword">$this</span>->getFromPayload(<span class="hljs-string">'user'</span>);
}
}
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.