0

I have figure it out how to validate one sheet in Laravel Excel. But I don't know how to differentiate validation by each sheet? Someone knows how to do it?

I have these validations for my sheet-1

return [
    "*.0" => ['required', 'integer'],
    "*.1" => ['required'],
    "*.2" => ['required', 'max:5'],
];

And validations for sheet-2

return [
    "*.0" => ['required'],
    "*.1" => ['required', 'exists:users'],
    "*.2" => ['required'],
    "*.3" => ['required', 'alpha'],
];
amrezzd
  • 1,787
  • 15
  • 38
schutte
  • 1,949
  • 7
  • 25
  • 45
  • When dealing with multiple sheets in Laravel Excel, each sheet should have a separate import/export file. You then combine those sheets by using a parent import/export and the `WithMultipleSheets` concern. So to import/export 2 sheets, you need a total of 3 files. You don't need to differentiate between the validations because they should each be in different files. – matticustard May 17 '21 at 03:58
  • @matticustard thanks for the tip sir. Yeah I just realized that we can create a parent import for two imports and add with each validation. thanks again. i'll close this. – schutte May 17 '21 at 07:57

1 Answers1

0

You can separate the validation by sheet index so that each sheet will have it's own validation. To do that you need to implement WithMultipleSheets contract. In your case that would be like this:

namespace App\Imports;

use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Concerns\WithValidation;

class SheetImport implements WithMultipleSheets
{
    public function sheets(): array
    {
        return [
            0 => new class implements ToCollection, WithValidation
            {
                public function rules(): array
                {
                    return [
                        "*.0" => ['required', 'integer'],
                        "*.1" => ['required'],
                        "*.2" => ['required', 'max:5'],
                    ];
                }
            },
            1 => new class implements ToCollection, WithValidation
            {
                public function rules(): array
                {
                    return [
                        "*.0" => ['required'],
                        "*.1" => ['required', 'exists:users'],
                        "*.2" => ['required'],
                        "*.3" => ['required', 'alpha'],
                    ];
                }
            },
        ];
    }
}

Note that sheet indices start at zero. You can also create sheep import classes separately as explained at Laravel Excel - Multiple Sheets. The point is that you return sheet import objects from sheets method.

amrezzd
  • 1,787
  • 15
  • 38