1

why get undefined offset when importing excel file to the database using laravel.

UserImport.php

public function model(array $row)
{
    var_dump($row);
    
    return new User([
        'name' =>$row[0],
        'email'=>$row[1],
        'password' => Hash::make('password'),

    ]);
}

UserImportController

public function store(Request $request){

    $file = $request->file('file');
    Excel::import(new UsersImport, $file);
    return back()->withStatus('Successfully');
}

when uploading the excel file, display it like this. enter image description here

I used var_dump() to see the array. I entered 4 rows in the excel file. But display 5 array data. Why that??? (display in entered image. )

2 Answers2

0

I believe it is because of the new line at the end of the file.

You should check if it contains only a new line and skip the import.

  • 1
    I added if condition to UserImport.php if($row[0] !=""){ return new User([ 'name' =>$row[0], 'email'=>$row[1], 'password' => Hash::make('password'), ]); } – R.W.S. Maleesha Mar 26 '21 at 13:53
0

set if condition for UserImport.php

if($row[0] !=""){ 
    return new User([ 
        'name' =>$row[0], 
        'email'=>$row[1], 
        'password' => Hash::make('password'), 
   ]); 
}