laravelmaatwebsite-excel

Laravel model doesn't create when importing exel using maatwebsite/excel


I am using Laravel and want to import users from an Excel file to the project's database. so I installed the maatwebsite/excel package.
The problem is when I call this importer nothing is added to the project's database but table auto_increment is increasing.

enter image description here

There is no any data in database but auto_increment is 86.

App\Imports\UserImport.php

<?php

namespace App\Imports;

use App\Models\Position;
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class UsersImport implements ToModel, WithHeadingRow
{

    public function model(array $row)
    {
            User::create([
                'person_code' => $row['prsnly'],
                'username' => $row['prsnly'],
                'national_code' => $row['kd_mly'],
                'password' => $row['kd_mly'],
                'is_active' => User::ACTIVE
            ]);
        }

    }


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


}

This is my route to call this function:

routes/web.php

<?php

use App\Imports\UsersImport;
use Illuminate\Support\Facades\Route;
use Maatwebsite\Excel\Facades\Excel;

Route::get('import-chart', function () {
    Excel::import(new UsersImport, public_path('chart.xlsx'));
});

I added properties to the $fillable of the user model.


Solution

  • This problem was solved with two changes.

    First, removing cast for password in User model:

    protected $casts = [
        'password' => 'hashed'
    ];
    

    Second, replace User::create to return new User

    return new User([
        'person_code' => $row['prsnly'],
        'username' => $row['prsnly'],
        'national_code' => $row['kd_mly'],
        'password' => $row['kd_mly'],
        'is_active' => User::ACTIVE
    ]);