cosminc's avatar

Fetch error message generated by file upload validator

Hello everybody,

I'm building a form with multiple fields and among those I also have a file upload input.

I'm trying to display an error message after each input, but it seems that this logic doesn't work for the file upload one.

<div class="form-group">
    <label for="attachment">Attachment</label>
    <input id="attachment" type="file" class="form-control" name="attachment">
</div>

@if ($errors->has('attachment'))
    <span class="error">
        <strong>{{ $errors->first('attachment') }}</strong>
    </span>
@endif 

It seems that I can only get the error from the input field with a code like this:

@if ($errors->any())
    @foreach ($errors->all() as $error)
        <div class="alert alert-danger" role="alert">
            {{ $error }}
        </div>
    @endforeach
@endif 

So my question is: what do I need to do in order to fetch the error for that specific field?

Thank you.

0 likes
8 replies
cosminc's avatar

Here goes:

$validatedData = $request->validate([
    'firstname' => 'required|max:32|regex:/^[. a-zA-Z0-9_-]+$/',
        'lastname' => 'required|max:32|regex:/^[. a-zA-Z0-9_-]+$/',
        'email' => 'required|email',
        'message' => 'required|max:1000',
     'captcha' => 'required|captcha',
     'attachment' => 'file|max:1024|mimes:jpeg,bmp,png'
]);
Grelav's avatar

what is the result you see when

dd(errors)
cosminc's avatar

This is the output when only the input field is invalid:

ViewErrorBag {#561 ▼
  #bags: array:1 [▼
    "default" => MessageBag {#552 ▼
      #messages: array:1 [▼
        "attachment" => array:2 [▼
          0 => "The attachment may not be greater than 1024 kilobytes."
          1 => "The attachment must be a file of type: jpeg, gif, png."
        ]
      ]
      #format: ":message"
    }
  ]
}
Grelav's avatar

try

@if ($errors->has('attachment.1'))
    <span class="error">
        <strong>{{ $errors->first('attachment.1') }}</strong>
    </span>
@endif 

or '0' instead of '1'

Please or to participate in this conversation.