Skip to content
Advertisement

How to save data to db using laravel import?

I have prepared code below, and I’m using the dump to trace if it passed to models’ create function.

When I checked in the database there is no data added, I’m just wondering why it does not have when it is already passed in User::create function (verified by string “created” below in the picture).


These are the dump datas returned (note: i’m using picture for better visualization)

enter image description here


And here is my code in UserImport.php

public function model(array $row)
{
    User::create([
        'name' => $row[0],
        'birthdate' => $row[1],
        'gender' => $row[2],
    ]);

    dump('created');
}

public function rules(): array
{
    return [
        '1' => ['required'],
        '2' => ['required'],
    ];
}

And about dumping the validations message is my UserController (to shorten, i will just post the important parts)

catch (MaatwebsiteExcelValidatorsValidationException $e)
{
    $failures = $e->failures();
    dd($failures);
}

Advertisement

Answer

This is the expected behavior. Laravel Excel uses database transactions to ensure data integrity when performing imports. You have failures, so the entire transaction was rolled back.

https://docs.laravel-excel.com/3.1/imports/validation.html#database-transactions

#Database transactions
The entire import is automatically wrapped in a database transaction, that means that every error will rollback the entire import. When using batch inserts, only the current batch will be rollbacked.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement