spatie/laravel-interacts-with-payload
Inject extra data into the payload of every queued job in your Laravel app. Add keys via a facade (e.g., current user, request context), then access them inside jobs with the InteractsWithPayload trait using getFromPayload().
Installation:
composer require spatie/laravel-interacts-with-payload
Publish the config (if needed) with:
php artisan vendor:publish --provider="Spatie\InteractsWithPayload\InteractsWithPayloadServiceProvider"
First Use Case:
Inject a user into all jobs via a Service Provider (e.g., AppServiceProvider):
use Spatie\InteractsWithPayload\Facades\AllJobs;
public function boot()
{
AllJobs::add('initiating_user', fn() => auth()->user());
}
Retrieve in Jobs:
Use the InteractsWithPayload trait in any job:
use Spatie\InteractsWithPayload\Concerns\InteractsWithPayload;
class ProcessOrder implements ShouldQueue
{
use InteractsWithPayload;
public function handle()
{
$user = $this->getFromPayload('initiating_user');
}
}
AppServiceProvider or a dedicated PayloadServiceProvider).AllJobs::add('tenant_id', fn() => Tenant::current()->id);
AllJobs::add('request_id', fn() => request()->header('X-Request-ID'));
AllJobs::add('is_admin', fn() => auth()->user()->isAdmin());
AllJobs::addForJob():
AllJobs::addForJob(ProcessOrder::class, 'priority', fn() => 10);
$user = $this->getFromPayload('initiating_user');
if (!$user) {
throw new \RuntimeException("User not found in payload.");
}
AllJobs::setPayload():
AllJobs::setPayload('initiating_user', User::factory()->create());
Payload Serialization:
fn() => $model->toArray() for complex objects.Late Binding Issues:
AllJobs::add() are evaluated once (when the job is dispatched), not per execution.handle() if dynamic.Job Dispatch Context:
auth() or request() data is available at dispatch time.Performance:
AllJobs::addIf() to conditionally add payloads:
AllJobs::addIf(fn() => config('app.debug'), 'debug_mode', true);
Inspect Payloads: Dump the full payload in a job to debug:
dd($this->getPayload());
Clear Cached Payloads: If payloads seem stale, clear the cache:
php artisan cache:clear
Custom Payload Sources:
Extend the PayloadResolver class to fetch data from non-standard sources (e.g., Redis, database):
AllJobs::add('cache_key', new CustomPayloadResolver());
Payload Transformers: Transform payload values before injection:
AllJobs::add('formatted_date', fn() => now()->format('Y-m-d'));
Middleware for Payloads: Use Laravel middleware to set payloads dynamically (e.g., based on API routes):
AllJobs::add('api_version', fn() => request()->header('Accept-Version'));
AllJobs::add() calls overwrite earlier ones for the same key. Use unique keys or addForJob() for specificity.How can I help you explore Laravel packages today?