首页 > 解决方案 > Laravel 5.8 如何获得工作 ID?

问题描述

我正在尝试在我的工作中获取工作 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
    }
}

标签: phplaravellaravel-5.6laravel-5.7laravel-5.8

解决方案


以下将允许您获取作业 ID。尝试复制下面的代码并使用简单的路由进行调度。

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

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

并通过以下路线对其进行测试。

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

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

终端返回作业 ID

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

php artisan queue:work redis --tries=3

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


推荐阅读