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

Mike Ross
  • 2,942
  • 5
  • 49
  • 101

1 Answers1

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],
    ]);
}
Arthur Samarcos
  • 3,262
  • 22
  • 25
  • 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. – Arthur Samarcos Nov 22 '18 at 00:01
  • I think you are right. How do i skip emptyrow from validating? – Mike Ross Nov 22 '18 at 00:02
  • that skips the whole row if the first cell is blank. – Mike Ross Nov 22 '18 at 00:08
  • Well... You are the one saying the first cell is required. :P – Arthur Samarcos Nov 22 '18 at 00:09
  • 1
    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. – Mike Ross Nov 22 '18 at 00:12
  • In general a row is a collection of fields that belongs to a single element. Isn't that the case for you? When you say the first cell is required, this means that your whole row is invalid if first row is not provided, that's exactly what the system should be doing, it's normal behaviour. Maybe you can clarify what you are trying to achieve. – Arthur Samarcos Nov 22 '18 at 00:18