Ways to Pass Parameters to Laravel job.

There are 2 ways to pass parameters to a dispatching job in Laravel.
First is simply call dispatch() or dispatchNow() as per requirement on your Job class like calling a static method on a class:
YourJob::dispatch(argument1, argument2, argument3);
Second is simply pass arguments while creating an instance/object of Job class then pass the object to dispatch method(always available in the controller) like:
$this->dispatchNow(new YourJob(argument1, argument2, argument3));
The arguments will be available in the constructor, can you assign them to class local variable properties and use anywhere in Job class.

Let consider below example job:
<?php
    namespace App\Jobs;

    use Illuminate\Bus\Queueable;
    use Illuminate\Queue\SerializesModels;
    use Illuminate\Queue\InteractsWithQueue;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Illuminate\Foundation\Bus\Dispatchable;

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

        private $a;
        private $b;
        private $c;

        /**
         * Create a new job instance.
         *
         * @return void
         */
        public function __construct(string $a, int $b, int $c)
        {
            $this->a = $a;
            $this->b = $b;
            $this->c = $c;
        }

        /**
         * Execute the job.
         *
         * @return array
         */
        public function handle()
        {
            return [$this->a,
                    $this->b,
                    $this->c
                    ];
        }
    }
  	
Then parameters can be passed to this job as below:
Testjob::dispatch('hello', 5, 2);
OR
$this->dispatchNow(new Testjob('hello', 5, 2));

This will give output like : 

array:3 [
        0 => "hello"
        1 => 5
        2 => 7
    ]
    
Feel free to leave a comment in case any query related to this.

Comments

Post a Comment

Popular posts from this blog

Using Virtual Columns in Laravel - Accessors and Appends

How to Show Cookie Policy Consent or GDPR Popup in Laravel using Cookie.

Postman Collection Run - How to Test File Uploading API on CircleCi or Jenkins