0

I'm executing Export, Import to Excel in Laravel. But I have an error

Undefined index: code

in a file AlumniImport.php. Thank you for help!

AlumniImport.php

namespace App\Imports;

use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Illuminate\Support\Facades\Hash;

class AlumniImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new User([
            'code'          => $row["code"],
            'first_name'    => $row["first_name"],
            'last_name'     => $row["last_name"],
            'username'      => $row["username"],
            'password'      => Hash::make($row["password"]),
            'tel'           => $row["tel"],
            'email'         => $row["email"],
            'gender'        => $row["gender"],
            'birthday'      => $row["birthday"],
            'address'       => $row["address"],
            'status_id'     => $row["status_id"],
        ]);
    }
}

AlumniController.php

// Excel
use App\Imports\AlumniImport;
use App\Exports\AlumniExport;
use Excel;
class AlumniController extends Controller
{
 public function import()
    {
        Excel::import(new AlumniImport,request()->file('file'));
        return back();  
    }
}

Example of data in Excel:

code    first_name  last_name   username    password    tel     email      gender birthday  address status_id
B8888   John        Smith       johnsmith   123456    123456    [email protected] Male 4/9/1998   USA 1 
B7777   Tom         Cruise      tomcruise   123456    123456    [email protected] Male    4/5/1998 Canada 1 
B6666   Lena        Do          lenado      123456    123456    [email protected]    Male    9/4/1997    USA 2
7
  • is there a column "code" in your excel file ? do you have headers in the first line of your excel ? would be easier if you provided a sample of the excel file in question. Commented Jul 18, 2019 at 8:33
  • Sure, Row 1: code,first_name,last_name,username,password,tel,email,gender,birthday,address,status_id Row 2: data of row1 ** Row 3: ** data of row2 Commented Jul 18, 2019 at 8:44
  • Please post the whole error that you're getting and the example excel file on which it is failing. Commented Jul 18, 2019 at 8:44
  • If I comment little hard read, I'm sorry because I'm a new contributor. Commented Jul 18, 2019 at 8:48
  • I get error's: Undefined index: code. And file alumnies_db.xlsx code first_name last_name username password tel email gender birthday address status_id B8888 John Smith johnsmith 123456 123456 [email protected] Male 4/9/1998 USA 1 B7777 Tom Cruise tomcruise 123456 123456 [email protected] Male 4/5/1998 Canada 1 B6666 Lena Do lenado 123456 123456 [email protected] Male 9/4/1997 USA 2 Commented Jul 18, 2019 at 8:59

2 Answers 2

2

You can confirm my suggestion by doing a var_dump($row);die();

what i found on the package Maatwebsite, the $row has numeric indexes.

try this

class AlumniImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new User([
            'code'          => $row[0],
            'first_name'    => $row[1],
            'last_name'     => $row[2],
            'username'      => $row[3],
            'password'      => Hash::make($row[4]),
            'tel'           => $row[5],
            'email'         => $row[6],
            'gender'        => $row[7],
            'birthday'      => $row[8],
            'address'       => $row[9],
            'status_id'     => $row[10],
        ]);
    }
}

-----edit-----

dont forget to put the fields in the $fillable of the User::class

class User extend Model
{
    protected $fillable = ['code','first_name', 'last_name', 'username', 'password', 'tel', 'email', 'gender', 'birthday', 'address', 'status_id'];
    .....
}

if you dont wanna put these fields as fillable and i dont recommend you to do it (especially for the password field) you can do it this way;

class AlumniImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        $user = new User();
        $user->code = $row[0];
        $user->first_name = $row[1];
        $user->last_name = $row[2];
        $user->username = $row[3];
        $user->password = Hash::make($row[4]);
        $user->tel = $row[5];
        $user->email = $row[6];
        $user->gender = $row[7];
        $user->birthday = $row[8];
        $user->address = $row[9];
        $user->status_id = $row[10];
        return $user;
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you suggestion, but now I get this error: SQLSTATE[HY000]: General error: 1364 Field 'code' doesn't have a default value (SQL: insert into users (updated_at, created_at) values (2019-07-18 12:09:45, 2019-07-18 12:09:45))
@RusKhanh did you set the protected $fillable in the User::class model ?
Yep, when I input follow your suggestion is Add var_dump($row) or die();, I get the data in my file data.xlsx. But, why I can't import data. Data return from var_dump($row) above: array(11) { ["code"]=> string(5) "B7777" ["first_name"]=> string(4) "John" ["last_name"]=> string(5) "Smith" ["username"]=> string(9) "johnsmith" ["password"]=> float(123456) ["tel"]=> float(123456) ["email"]=> string(15) "johnsmith@gmail" ["gender"]=> string(4) "Male" ["birthday"]=> float(32755) ["address"]=> string(3) "USA" ["status_id"]=> float(1) }
@RusKhanh i've added an alternative in my solution, check the edit
Yes. Thank you so much @N69S
0

Add this line in your AlumniImport class:

use Maatwebsite\Excel\Concerns\WithHeadingRow;

After this, include WithHeadingRow in your AlumniImport class like this:

class AlumniImport implements ToModel,WithHeadingRow

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.