Search code examples
phplaravelfile-uploadqueuejob-batching

How to solve failed job batching in Laravel


I made a job batching to insert csv into database.

Here is the method:

public function upload()
{
    if(request()->has('file')){
        $data = file(request()->file);
        
        // Chunking file
        $chunks = array_chunk($data,5);
       
        $batch = Bus::batch([])->dispatch();

        foreach($chunks as $chunk){
            
            $data = array_map('str_getcsv',$chunk);

            $batch->add(new BinlocCsvProcess($data));
        } 

        return $batch;
    }
    return 'please upload file';
}

And this is my Job class:

class BinlocCsvProcess implements ShouldQueue {

public $data;
/**
 * Create a new job instance.
 *
 * @return void
 */
public function __construct($data)
{
    $this->data = $data;
}

/**
 * Execute the job.
 *
 * @return void
 */
public function handle()
{
    foreach($this->$data as $item){
        Binloc::create($item);
    } 
}
}

I don't know how to get the error why it doesn't work and I don't have any idea how to solve it.


Solution

  • The error appear because line foreach($this->$data as $item). You should remove $, so your code should be like this foreach($this->data as $item).