0
votes

I'm new to laravel framework. i'm getting an error

ErrorException (E_WARNING) Illegal string offset 'customerid'

I tried to import an excel file and show the data in a datatable in same page. I got an error:

call to undefined method maatwebsite/Excel/Excel::load().

To fix this error I downgraded the maatwebsite/excel version from 3.1 to ~2.1.0 then I updated composer using composer update. Then I got another error "continue " targeting switch is equivalent to break -- I fixed it by changing continue to continue 2 in OLE.php file.

Now I'm getting a new error

"ErrorException (E_WARNING) Illegal string offset 'customerid'"

public function import_csv(Request $request)
{
    $this->validate($request, [
        'select_file' => 'required|mimes:xls,xlsx',
    ]);

    $path = $request->file('select_file')->getRealPath();

    $data = Excel::load($path)->get();

    if ($data->count() > 0) {
        foreach ($data->toArray() as $key => $value) {
            foreach ($value as $row) {
                $insert_data[] = [
                    'customerid'  => $row['customerid'],
                    'enquiryid'   => $row['enquiryid'],
                    'productid'   => $row['productid'],
                    'productname' => $row['productname'],
                    'quantity'    => $row['quantity'],

                ];
            }
        }

        if (!empty($insert_data)) {
            DB::table('enquiryproducts')->insert($insert_data);
        }
    }

    return back()->with('success', 'Excel Data Imported successfully.');
}

import_csv.blade.php:

<form id="upload_csv_form" action="{{ url('/import_csv/import') }}" method="POST" enctype="multipart/form-data">
    @csrf
    <div class="row">
        <div class="col-lg-6 col-md-12">
            <fieldset class="form-group">
                <input type="file" name="select_file" accept=".csv" class="form-control-file" id="select_file">
            </fieldset>
            <button type="submit" name="upload_csv" class="btn btn-success">Upload Enquiry Products</button>
        </div>
    </div>
</form>
1
It mean $row does not have index customerid, use var_dump($row) to see the content of the arraycatcon
Possible duplicate of Illegal string offset Warning PHPJosh

1 Answers

1
votes

You don't have to make another foreach loop for $value.

Try this:

if($data->count() > 0)
{
    foreach($data as $key => $value)             
    $insert_data[] = array(
       'customerid'   => $value['customerid'],
       'enquiryid'   => $value['enquiryid'],
       'productid'   => $value['productid'],
       'productname' => $value['productname'],
       'quantity'    => $value['quantity'],    
    );                
}