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

Technical Evaluation

Architecture Fit

  • Pros:

    • Decoupled Payload Injection: The package provides a clean, centralized way to inject dynamic payload data (e.g., auth user, request context, or system metadata) into all queued jobs without modifying individual job classes. This aligns well with Laravel’s queue system and promotes DRY (Don’t Repeat Yourself) principles.
    • Trait-Based Design: Leverages Laravel’s InteractsWithPayload trait, ensuring minimal boilerplate for job classes. This is low-friction for adoption across existing or new jobs.
    • Facade API: The AllJobs facade offers a declarative way to define payload variables (e.g., AllJobs::add('user', fn() => auth()->user())), making configuration explicit and maintainable.
    • Context Awareness: Ideal for scenarios requiring cross-cutting concerns (e.g., audit logging, tenant context, or request-scoped data) in async workflows.
  • Cons:

    • Global Scope: Payload variables are app-wide, which may lead to unintended side effects if not carefully managed (e.g., injecting sensitive data like auth()->user() in jobs that shouldn’t access it).
    • No Payload Isolation: All jobs share the same payload context, which could couple unrelated jobs if overused (e.g., a SendEmailJob shouldn’t depend on a ProcessPaymentJob's payload).
    • Limited Payload Customization: No built-in support for job-specific payload overrides or conditional injection (e.g., injecting data only for certain job types).

Integration Feasibility

  • Laravel Compatibility:
    • Seamless: Works out-of-the-box with Laravel’s queue system (database, Redis, etc.) and job classes. No changes to Laravel’s core are required.
    • Version Support: Tested with recent Laravel versions (as of 2025-03-08), but backward compatibility should be verified for legacy apps (e.g., Laravel 8+).
  • Dependency Overhead:
    • Minimal: Only requires the package and its facade/trait. No additional services or databases are needed.
  • Testing:
    • Unit Test Friendly: Payload injection can be mocked easily in tests (e.g., stubbing AllJobs::add() or getFromPayload()).
    • Integration Testing: May require testing job payloads in isolation to avoid flakiness from shared context.

Technical Risk

  • Risk 1: Over-Engineering Shared State
    • Impact: Injecting too much global state (e.g., auth()->user() in all jobs) could lead to tight coupling or security risks (e.g., leaking auth data in long-running jobs).
    • Mitigation: Use the package selectively (e.g., only for jobs that explicitly need shared context) and validate payload data in jobs (e.g., check if $user is null or authorized).
  • Risk 2: Performance Overhead
    • Impact: If payload variables are expensive to compute (e.g., querying a database for every job), this could degrade queue performance.
    • Mitigation: Cache or lazy-load payload data where possible (e.g., AllJobs::add('user', fn() => cache()->remember('user:payload', ...))).
  • Risk 3: Breaking Changes
    • Impact: The package is actively maintained, but breaking changes (e.g., facade/trait API shifts) could require refactoring.
    • Mitigation: Monitor the release notes and pin versions in composer.json.

Key Questions

  1. Use Case Alignment:
    • Are we injecting shared context (e.g., user, tenant, request data) into all jobs, or only specific ones? If the latter, this package may be overkill (consider job-specific payloads instead).
  2. Security:
    • What sensitive data (if any) will be injected? How will we sanitize/validate payload data in jobs?
  3. Testing Strategy:
    • How will we mock payload data in unit/integration tests? Will we need a PayloadTestHelper?
  4. Performance:
    • Are payload variables computationally expensive? If so, how will we optimize (e.g., caching)?
  5. Alternatives:
    • Could we achieve the same with Laravel’s built-in resolve() method or job middleware? When would this package be strictly necessary?
  6. Monitoring:
    • How will we log/debug payload data in failed jobs? Will we need custom error handling?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Native Integration: Designed for Laravel’s queue system (supports ShouldQueue, Job, and Command jobs). Works with all queue drivers (database, Redis, sync).
    • Artisan Commands: Can inject payloads into Artisan commands (via InteractsWithPayload trait), enabling reuse across CLI workflows.
  • PHP Version:
    • Compatibility: Requires PHP 8.0+ (as of 2025). Verify compatibility with your app’s PHP version.
  • Package Dependencies:
    • No Conflicts: Only depends on Laravel core and spatie/laravel-package-tools. No external services or databases.

Migration Path

  1. Assessment Phase:
    • Audit existing jobs to identify shared context needs (e.g., user, tenant, request data).
    • Decide if global injection (this package) or job-specific payloads (e.g., constructor injection) is better.
  2. Pilot Implementation:
    • Start with non-critical jobs (e.g., logging, notifications) to test payload injection.
    • Example:
      // app/Providers/AppServiceProvider.php
      AllJobs::add('initiator', fn() => auth()->user());
      AllJobs::add('request_id', fn() => request()->header('X-Request-ID'));
      
    • Update a single job to use getFromPayload():
      use Spatie\InteractsWithPayload\Concerns\InteractsWithPayload;
      
      class LogActivityJob implements ShouldQueue {
          use InteractsWithPayload;
      
          public function handle() {
              $user = $this->getFromPayload('initiator');
              // ...
          }
      }
      
  3. Gradual Rollout:
    • Roll out to job batches (e.g., by feature/module) to minimize risk.
    • Use feature flags to toggle payload injection for specific jobs if needed.
  4. Deprecation Plan:
    • If using this for temporary needs, plan to remove payloads after migration (e.g., replace with job-specific data).

Compatibility

  • Job Types:
    • Works with all Laravel job classes (ShouldQueue, Job, Command).
    • Does not support: Non-Laravel jobs (e.g., raw queue strings) or third-party job classes without the trait.
  • Payload Data Types:
    • Supports any serializable data (models, arrays, primitives). Non-serializable data (e.g., closures) will fail.
  • Queue Workers:
    • No changes needed for Laravel Horizon, Supervisor, or default queue workers.

Sequencing

  1. Prerequisites:
    • Laravel 8.0+ (verify with your version).
    • PHP 8.0+.
    • Composer installed.
  2. Installation:
    composer require spatie/laravel-interacts-with-payload
    
    Publish config (if needed):
    php artisan vendor:publish --provider="Spatie\InteractsWithPayload\InteractsWithPayloadServiceProvider"
    
  3. Configuration:
    • Define payload variables in a service provider (e.g., AppServiceProvider).
    • Example:
      AllJobs::add('tenant_id', fn() => Tenant::current()->id);
      AllJobs::add('locale', fn() => app()->getLocale());
      
  4. Job Integration:
    • Add use InteractsWithPayload to job classes.
    • Use getFromPayload('key') to access data.
  5. Testing:
    • Write unit tests for payload injection (mock AllJobs).
    • Test edge cases (e.g., missing payload keys, non-serializable data).
  6. Monitoring:
    • Add logging for payload data in jobs (e.g., Log::debug('Payload:', $this->getFromPayload('*'))).
    • Monitor queue performance for payload computation overhead.

Operational Impact

Maintenance

  • Pros:
    • Centralized Configuration: Payload variables are defined in one place (e.g., AppServiceProvider), reducing boilerplate across jobs.
    • Easy Updates: Changing payload data (e.g., adding
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