Search code examples
laravellaravel-controllerlaravel-jobs

Laravel: Passing a class name from a Controller to a Job


I'm trying to pass a certain class name from the controller to a job file through

Job::dispatch($className);

I've tried passing it as a string and passing it as a ClassName::class but none of these methods work

The code in the Job file looks something along the lines of this:

<?php

namespace App\Jobs;

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


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

    protected $products;
    protected $jobName;

    public function __construct($products, $jobName)
    {
        $this->products = $products;
        $this->jobName = $jobName;
    }

    /**
     * Execute the jobName.
     *
     * @return void
     */
    public function handle()
    {
        $productArrays = array_chunk($this->products, 5000);

        foreach($productArrays as $productArray){
            $this->jobName::dispatch($productArray);
        }
    }
}

the $jobname variable is the className I'm trying to pass. I also need to note that I'm passing the classname of a different Job from the Controller, by which I mean the job handler is supposed to call another Job through the variable.


Solution

  • I do not think your syntax is working, an alternative approach would be to do it like this.

    dispatch(new $this->jobName($productArray));