[英]Laravel - Passing Request to Queue Job
我無法將請求傳遞到隊列handle()
作業
public function handle(Request $request) | package.json*
{ | phpunit.xml*
Log::alert('starting process'); | readme.md*
Log::alert($request); | server.php*
|~
if (strpos($request->status, 'Approved') !== false) { |~
$name = Name::where('mId', '=', $request->mId)->get()->first(); |~
|~
$client = new Client(); |~
|~
$client->request('POST', 'http://127.0.0.1:5000/api/email', [ |~
'json' => [ |~
'type' => $request->type, |~
'name' => $name->name,
] |~
]); |~
}
實際上, $request
空。 如果刪除Request
並僅保留handle($request)
則會得到此堆棧:
Too few arguments to function App\\Jobs\\PostAlfred::handle(), 0 passed and exactly 1 expected in
當表單更新時,我從控制器調用此函數。
public function update(UpdateRequest $request) |▸ vendor/
{ | artisan*
$redirect_location = parent::updateCrud($request); | composer.json* | composer.lock*
PostMyJob::dispatch($request);
我嘗試添加UpdateRequest
,例如: handle(UpdateRequest $request)
,然后出現授權錯誤。
不知道如何進行。
當您將任何參數傳遞給
dispatch
函數時,這些參數將在作業的constructor
函數中傳遞,而不是在handle
方法中傳遞。
參見文檔The arguments passed to the dispatch method will be given to the job's constructor
在您的工作中執行以下操作:
class SomeJob extends Job{
private $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function handle()
{
if (strpos($this->request->status, 'Approved') !== false) {
$name = Name::where('mId', '=', $this->request->mId)->get()->first();
$client = new Client();
$client->request('POST', 'http://127.0.0.1:5000/api/email', [
'json' => [
'type' => $this->request->type,
'name' => $name->name,
]
]);
}
}
}
請記住,請求僅存在於實際HTTP請求的上下文中。 它僅在您的應用正在處理該請求時存在。 當您的隊列工作者開始將作業從隊列中取出時,沒有“請求”。 Laravel無法為您提供請求的實例,因為沒有實例。
您需要做的是顯式傳遞您的工作所需的信息,以履行其職責。 如果只需要輸入請求,則可以執行類似的操作-這將為作業的構造函數提供輸入數組。
PostMyJob::dispatch($request->all())
public function __construct(array $input)
{
$this->input = $input;
}
您可能已經看到了Eloquent模型傳遞到工作中的示例,但不要讓您以為整個類都將按原樣提供給處理程序。 Laravel足夠聰明,可以在處理工作時為您重新獲取Eloquent模型,但是如前所述,它無法為您獲取原始請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.