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:
Let consider below example job:
This will give output like :
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.
helped a lot, thanks. But suggestion: remove this background color, it is difficult to read
ReplyDeleteThanks for your feedback, i have removed the background.
Deletethank you!!
ReplyDeleteWelcome!!
Delete