Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Interacts With Payload Laravel Package

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().

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Installation:

    composer require spatie/laravel-interacts-with-payload
    

    Publish the config (if needed) with:

    php artisan vendor:publish --provider="Spatie\InteractsWithPayload\InteractsWithPayloadServiceProvider"
    
  2. 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());
    }
    
  3. 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');
        }
    }
    

Implementation Patterns

1. Centralized Payload Injection

  • Where: Register payloads in a Service Provider (e.g., AppServiceProvider or a dedicated PayloadServiceProvider).
  • Why: Avoids repeating logic across jobs and keeps payload definitions in one place.
  • Example:
    AllJobs::add('tenant_id', fn() => Tenant::current()->id);
    AllJobs::add('request_id', fn() => request()->header('X-Request-ID'));
    

2. Dynamic Payloads

  • Use closures to compute values dynamically (e.g., current user, request data, or runtime conditions):
    AllJobs::add('is_admin', fn() => auth()->user()->isAdmin());
    

3. Job-Specific Overrides

  • Override payloads for specific jobs using AllJobs::addForJob():
    AllJobs::addForJob(ProcessOrder::class, 'priority', fn() => 10);
    

4. Payload Validation

  • Validate payloads in jobs to fail fast:
    $user = $this->getFromPayload('initiating_user');
    if (!$user) {
        throw new \RuntimeException("User not found in payload.");
    }
    

5. Testing

  • Mock payloads in tests using AllJobs::setPayload():
    AllJobs::setPayload('initiating_user', User::factory()->create());
    

Gotchas and Tips

Pitfalls

  1. Payload Serialization:

    • Only serializable data (e.g., arrays, primitives, Eloquent models) works. Avoid closures or non-serializable objects.
    • Fix: Use fn() => $model->toArray() for complex objects.
  2. Late Binding Issues:

    • Closures in AllJobs::add() are evaluated once (when the job is dispatched), not per execution.
    • Fix: Use dependency injection or resolve values in the job’s handle() if dynamic.
  3. Job Dispatch Context:

    • Payloads are set when the job is dispatched, not when it runs. Ensure auth() or request() data is available at dispatch time.
    • Fix: Pass data explicitly or use middleware to set payloads before dispatch.
  4. Performance:

    • Overusing payloads can bloat job serialization. Keep payloads minimal.
    • Tip: Use AllJobs::addIf() to conditionally add payloads:
      AllJobs::addIf(fn() => config('app.debug'), 'debug_mode', true);
      

Debugging Tips

  • 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
    

Extension Points

  1. Custom Payload Sources: Extend the PayloadResolver class to fetch data from non-standard sources (e.g., Redis, database):

    AllJobs::add('cache_key', new CustomPayloadResolver());
    
  2. Payload Transformers: Transform payload values before injection:

    AllJobs::add('formatted_date', fn() => now()->format('Y-m-d'));
    
  3. 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'));
    

Config Quirks

  • Default Payloads: The package doesn’t ship with defaults. Define all payloads explicitly in your provider.
  • Priority: Later AllJobs::add() calls overwrite earlier ones for the same key. Use unique keys or addForJob() for specificity.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport