senrab
1 month ago
497
2
Laravel

Bail on first validation error in array

Posted 1 month ago by senrab

I am trying to validate multi-file upload where users can upload pictures.

In my controller I have

    protected $required = [
        'title'                     => ['required', 'string', 'max:200'],
       ...
        'description'               => ['required', 'string'],
        'attachments'               => ['bail', 'required', 'array', 'max:10'],
        'attachments.*'             => ['file', 'mimetypes:image/jpeg,image/png,image/gif', 'dimensions:min_width=500,min_height=500']
    ];
    protected $messages = [
        'attachments'               => 'At least one image larger than 500x500 is required.',
        'attachments.max'           => 'You may upload a maximum of 10 images.',
        'attachments.*.file'        => 'One of the images you have uploaded is not supported.',
        'attachments.*.mimetypes'   => 'One of the images you have uploaded is not supported.',
        'attachments.*.dimensions'  => 'One of the images you have uploaded is too small. Images should be at least 500x500.'
    ];

The validation bails if there are no images. That's perfect. I would like the validation to bail if one of the attachments.* rules fails. Right now, it isn't and it is sending back all the messages in the bag.

For example if I upload a CSV, I get two errors

array:1 [▼
  "attachments.0" => array:2 [▼
    0 => "One of the images you have uploaded is not supported."
    1 => "One of the images you have uploaded is too small. Images should be at least 500x500."
  ]
]
  • I assume attachments.*.dimensions is failing on the CSV and returning 0x0.
  • I don't know why *.mimetypes isn't throwing an error)
  • Finally, *.file is throwing an error expected.

I could solve this in the blade with this, hwoever it doesn't feel right.

      @if($errors->has('attachments.*') and !$errors->has('attachments'))
                                    <strong>{{current(current($errors->get('attachments.*')))}}</strong>
                             @endif

Is there a better way?

Please sign in or create an account to participate in this conversation.