Search code examples
laravelqueue

How to get the specific data from jobs payload command in Laravel?


I can get the command data from payload on jobs table:

$job = DB::table('jobs')->first();
$payload = json_decode($job->payload);
$raw_command = json_decode($job->payload)->data->command;
$command = unserialize($raw_command);
dd($command->notification);

The result is:

App\Notifications\TenderInProgress {#1527 ▼
  +id: "0788ee9a-62c2-4280-9954-fc1d679228a8"
  +locale: null
  #tender_id: 5
  +connection: null
  +queue: null
  +chainConnection: null
  +chainQueue: null
  +chainCatchCallbacks: null
  +delay: Carbon\Carbon @1678173780 {#1528 ▶}
  +afterCommit: null
  +middleware: []
  +chained: []
}

I can dump the value of id: dd($command->notification->id)

But cannot dump the value of tender_id: Cannot access protected property App\Notifications\TenderInProgress::$tender_id

How can I get the value of tender_id?


Solution

  • So, as I have stated on the comments, you have to use a Job Middleware, not read the content of a job (not directly).

    Lets create the middleware in app/Jobs/Middleware and lets call it TenderChecker.php:

    <?php
     
    namespace App\Jobs\Middleware;
     
    class TenderChecker
    {
        public function handle($job, $next)
        {
            if (Tender::findOrFail($job->tender_id)->status !== 'cancelled') {
                return $next($job); 
            }
    
            $job->delete();
        }
    }
    

    Do set the right check, I am just giving an example here. The idea is to check if the job should be executed, in your case, if tender_id model is not cancelled. I have no idea if you are using SoftDeletes or a status column, but do the logical check and if it passes the check, do execute return $next($job); so it continues checking middlewares until there are no more middlewares and reaches the job for normal execution.

    Now, your job would need to have the middleware method:

    use App\Jos\Middleware\TenderChecker;
    
    class YourJob
    {
        // ...
        public function middleware()
        {
            return [new TenderChecker];
        }
    }
    

    If the middleware passes, then the job is good to go and automatically executes . If the middleware "fails", then it will delete the job, because that is what you want to check/do.


    Here is an example of Laravel's officials middlewares (so you can see how they are used/built): https://github.com/laravel/framework/tree/10.x/src/Illuminate/Queue/Middleware

    And here is the official docs: https://laravel.com/docs/10.x/queues#job-middleware