Search code examples
phplaravelamazon-web-servicesamazon-sqslaravel-queue

Laravel and AWS SQS, How to read job payload / retrieve queue?


I struggling from last 3 days about how I can read queued job payload in Laravel.

What I've achieved till yet. Dispatch a job and see that it is available on AWS SQS queue. After that I've executed listener and worker for AWS to process queued jobs and I see that it is working fine as well.

Right now I am stuck on how I can read QUEUED job payload / messagebody / attributes from AWS SQS.

Here is my code example if possible than anyone from this whole community please help me.

<?php

   namespace App\Jobs;
   use App\CookieXrayConsentLog;
   use App\CookieXrayScript;
   use Carbon\Carbon;
   use Illuminate\Bus\Queueable;
   use Illuminate\Queue\SerializesModels;
   use Illuminate\Queue\InteractsWithQueue;
   use Illuminate\Contracts\Queue\ShouldQueue;
   use Illuminate\Foundation\Bus\Dispatchable;
   use Illuminate\Support\Facades\DB;
   use Illuminate\Support\Facades\Log;
   use Illuminate\Support\Facades\Queue;
   use Illuminate\Support\Facades\Storage;

   class QueueCookieConsent implements ShouldQueue
   {
       use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

       protected $job;

       // The maximum attempts of this job
       
       public $tries = 5;

       /**
       * Create a new job instance.
       *
       * @return void
       */
       public function __construct(array $data)
       {
           $this->job = $data;
           $this->onConnection('sqs');
           $this->onQueue('dev_consent');
       }

       /**
       * Execute the job.
       *
       * @return void
       */
       public function handle()
       {

           // Tried by these ways

           Log::info('job => ' .' This --- '. json_encode(Queue::pop()->payload()));


           Log::info('job => ' .' This --- '. json_encode($this->job));

       }
   }

Logs are printed if I remove this json_encode() from log info as mentioned above.


Solution

  • In your case you want to access $this->job->payload(), but you are overwriting the job variable in the constructor, with this line.

    $this->job = $data;
    

    Instead rename this to something else.

    $this->data = $data;
    

    Now you can access the payload like so.

    $this->job->payload()