Laravel 5.8 如何获取作业 ID?

Ken*_*eth 8 php laravel laravel-5.6 laravel-5.7 laravel-5.8

我正在尝试在我的工作中获取工作 ID。我尝试$this->job->getJobId()但它返回一个空字符串。

<?php

namespace App\Jobs\Notifications;

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\Auth;

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

    public function __construct($notification, $fireShutdown)
    {
        $this->notification = $notification;
        $this->fireShutdown = $fireShutdown;
    }

    public function handle()
    {
        dd($this->job->getJobId());

       // Some Code
    }
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*ank 8

以下将允许您获取作业 ID。尝试复制下面的代码并使用简单的路由发送它。

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        echo $this->job->getJobId();
    }
}
Run Code Online (Sandbox Code Playgroud)

和下面的路线来测试它。

Route::get('/trigger', function () {
    dd(dispatch(new \App\Jobs\TestJob()));
});
Run Code Online (Sandbox Code Playgroud)

在您的终端中,您现在应该看到以下内容,以及您给定作业的 ID。

终端返回作业 ID

如果您的队列侦听器没有运行,您可以通过在终端中键入以下内容来启动它

php artisan queue:work redis --tries=3
Run Code Online (Sandbox Code Playgroud)

如果您尝试将 id 返回到您的控制器/路由,由于异步/排队作业的性质,您无法使用异步/排队作业执行此操作。

  • @NicklasKevinFrank @kenneth Jeez!!刚刚找到[这个答案](/sf/ask/3274995951/ -工作队列),尝试了一下,**成功了**!这是我的行: `dump(app(\Illuminate\Contracts\Bus\Dispatcher::class)-&gt;dispatch(new TestQueue($source)));` 在浏览器中: #14 &lt;&lt; 真实数据库 ID (2认同)