MultiFile Upload Validation In Laravel (v5.2) / Pt.2

- this is using the same workflow as Here

** in v5.2 in-order to validate an array, the input HAVE to be named as ‘name.` but retrieving this input errors wont be possible, WHY ???
because laravel replace the ‘.
‘ with the item index so you can only display it by ‘name.0 / name.1 / etc…‘ which slightly got changed in v5.3, however with the solution below you will be able to validate ur multi-file upload just like any other input & still get a user friendly error which actually make sense.

** this is also the same solution as for v5.3 but with minor difference according to the changes made from v5.2 to v5.3

Update
if you prefer to use the native form-request instead Check

  • view
{{ Form::open(['route' => 'store.files', 'method' => 'POST', 'files'=>true]) }}
  {{ Form::file('photo[]', ['multiple']) }}
  {{ Form::submit('submit') }}
{{ Form::close() }}

@foreach ($errors->get('image') as $one)
  <li>{!! $one !!}</li>
@endforeach
  • validations\Post\StoreValidation
// ...

class StoreValidation
{

  // ...

  protected $error_container = [];


  protected function validate($request)
  {
    // add here any single input
    $rules = [
      // ...
    ];

    $validator = Validator::make($request->all(), $rules);

    $validator->after(function ($validator) use ($request) {

      $input_name = 'photo';

      // if no items found
      if ( ! $request->hasFile($input_name)) {
        $validator->errors()->add($input_name, \Lang::get('validation.required', ['attribute' => $input_name], \App::getLocale()));
      }

      // otherwise
      else {
        $regex = '/^.*?'.$input_name.'/';

        foreach ($request->file($input_name) as $one) {
          $v = Validator::make(
            [$input_name => $one],
            [$input_name => 'image|max:2048|etc...']
          );

          if ($v->fails()) {
            $new_name = "<strong>{$one->getClientOriginalName()}</strong>";
            $str = preg_replace($regex, $new_name, $v->errors()->getMessages()[$input_name][0]);
            $this->error_container[$input_name][] = $str;
          }
        }

        if ( ! empty($this->error_container)) {
            $validator->errors()->add($input_name, $this->error_container[$input_name]);
        }
      }
    });

    if ($validator->fails()) {
      throw new ValidationException(
        $validator, 
        $this->buildFailedValidationResponse(
          $request, 
          array_replace_recursive(
            $this->formatValidationErrors($validator),
            $this->error_container
          )
        )
      );
    }
  }
}

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.