0

I am implementing Laravel-Excel into my project and could not figure out the validation.

I try to upload the xlsx file with one row of data in it but still, the import throws required error.

Following is my EventResultImport code

namespace App\Imports;

use App\Models\Data\EventResult;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;

class EventResultImport implements ToModel, WithValidation, WithHeadingRow
{
    use Importable;

    public function model(array $row)
    {
        HeadingRowFormatter::default('none');

        return new EventResult([
            'event_id' => $row[0],
            'event_name' => $row[1],
        ]);
    }

    public function rules(): array
    {
        return [
            //'EventId' => 'required|numeric', Tried this
            //'*.EventId' => 'required|numeric', Tried this
            '0' => 'required|numeric'

        ];
    }
}

I get error on second-row event if there is numeric data in column EventId.

enter image description here

Thank you

1 Answer 1

1

You are implementing WithHeadingRow, so the attributes must match:

public function rules(): array
{
    return [
        'event_id' => 'required|numeric'
    ];
}

To skip nulls:

public function model(array $row)
{
    if (!isset($row[0])) {
        return null;
    }

    return new User([
        'name' => $row[0],
    ]);
}
Sign up to request clarification or add additional context in comments.

6 Comments

Message says you are missing an ID on row 2 and you said your file has only one row, so maybe your file has leftover data on row 2.
I think you are right. How do i skip emptyrow from validating?
that skips the whole row if the first cell is blank.
Well... You are the one saying the first cell is required. :P
first cell is required but there are other cells in the row and if the first is empty it will always skip the whole row and not validate.
|

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.