Skip to content

dispatch method does not respect ShouldBeUnique on jobs #45781

@ankurk91

Description

@ankurk91
  • Laravel Version: 9.48..0
  • PHP Version: 8.2
  • Database Driver & Version: MySql
  • Cache and Queue driver - Redis v7

Description:

Steps To Reproduce:

Create a test job:

<?php

namespace App\Jobs;

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

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

    public function __construct()
    {
        //
    }

    public function handle()
    {
        info("Running the job");
        sleep(3);
    }
}

Then create a Controller and dispatch the job via dispatch() helper available in all Controllers

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Jobs\TestJob;

class TestController extends Controller
{
    public function index()
    {
        // TestJob::dispatch(); // works as expected 
        // dispatch(new TestJob()); // works as expected
        
        $this->dispatch(new TestJob()); // causing the issue
    }
}

Start the worker

php artisan queue:work --sleep=3

Now hit the controller via a route twice, notice worker will process 2 jobs.

The problem lies here in this trait

return app(Dispatcher::class)->dispatch($job);

This method is dispatching the jobs in a different way which does not respect the ShouldBeUnique contract

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions