1

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 (\Maatwebsite\Excel\Validators\ValidationException $e)
{
    $failures = $e->failures();
    dd($failures);
}

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the direct answer sir. I know its out of the scope of the question, I would like to ask, is there any way we could implement like this, "save data, then if it fails to specific row, stop"?
Possibly, though it would require some customization. And disabling transactions is not advisable. I would probably lean toward the simpler solution which would be to skip over invalid rows. This could be handled by removing the built in Laravel Excel validation and simply checking whether those values are satisfactory within the model() method before calling User::create(). But you would have to handle the error reporting if you want to know what was skipped.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.