ImportValidatorHelper.php 834 B

12345678910111213141516171819202122232425262728293031
  1. <?php
  2. namespace App\Imports;
  3. use App\Http\Controllers\JsonResponseHelper;
  4. use Illuminate\Support\Collection;
  5. use Illuminate\Support\Facades\Validator;
  6. trait ImportValidatorHelper
  7. {
  8. use JsonResponseHelper;
  9. protected function validatorByCollection(Collection $collection, array $rules, array $messages = [])
  10. {
  11. $errors = [];
  12. foreach ($collection as $index => $item) {
  13. $validator = Validator::make($item->toArray(), $rules, $messages);
  14. if ($validator->fails()) {
  15. $errors[$index + 1] = [
  16. 'index' => $index + 1,
  17. 'errors' => $validator->errors()->all()
  18. ];
  19. }
  20. }
  21. if ($errors) {
  22. throw new \App\Exceptions\ValidationException(errors: array_values($errors));
  23. }
  24. }
  25. }