import excel sheet not working with laravel

247 Views Asked by At

Iam trying to import excel sheet to my project using maatwebsite package , i have done everything right but iam getting some error can not handle. it keep displaying message from file in vendor telling me that (Using $this when not in object context). Here is my code:

My Controller

public function excel(Request $request)
{
    Excel::import(new ProductsImport(),$request->file('sizes'));

    return redirect(route($this->route . '.index'))->with('message', trans('lang.added_s'));
}

vendor/maatwebsite/excel/src/Excel.php

public function import($import, $filePath, string $disk = null, string $readerType = null)
{
    $readerType = FileTypeDetector::detect($filePath, $readerType);
    //this line below is keeping making error ( Using $this when not in object context)
    $response   = $this->reader->read($import, $filePath, $readerType, $disk);

    if ($response instanceof PendingDispatch) {
        return $response;
    }

    return $this;
}
1

There are 1 best solutions below

0
Abderrahman Fodili On

according to the docs, you need to go to that ProductsImport file that you have created and specify what you want to do with the file. Do you want to get a collection or create models ? implement either "ToModel" or "ToCollection" and then add the corresponding the method

I usually chose ToCollection then do sth like this :

class ProductsImport implements ToCollection, WithHeadingRow
{
    public function collection(Collection $rows)
    {
        foreach ($rows as $row) 
        {
                Product::create([
                'name' => $row['name'],
               // add the other columns 
        ]);
        }
    }
}

You might also want to implement "WithHeadingRow" and add the method headingRow to tell the package where you're heading row is:

 public function headingRow(): int
{
    return 1;
}

Another thing you can do is store the file first before importing it. I do that to keep track of the files imported.

$file = $request->file('sizes') ;
$file_name = '' //decide file name here ;
$file>storeAs('public/'.$file_name.$file->clientExtension();

and then I would pass that to the Excel import method :

Excel::import(new ProductsImport(),public_path('storage/'.$file_name));

NB : do not mess with any vendor files.