'Displaying validation errors from an input array in Laravel

I am submitting an array of inputs to my controller like so:

<input id="box-1-nickname" name="box-nickname[]" class="form-control" type="text" placeholder="Required">
<input id="box-2-nickname" name="box-nickname[]" class="form-control" type="text" placeholder="Required">

I am doing some validation like this:

$validator = Validator::make(Input::all(), array(
        'supplies-count' => 'required|in:0,1,2,3,4',
    ));

$arrayValidator = Validator::make(Input::all(), []);

$arrayValidator->each('box-nickname', ['required|min:1|max:60']);

if( $validator->fails() || $arrayValidator->fails() ) {
    return Redirect::route('route-2')
           ->withErrors($arrayValidator)
           ->withInput();
}

The problem is when I try to check the errors like this it doesn't work:

if( $errors->has('box-1-nickname') ) { echo ' has-error'; }


Solution 1:[1]

Displaying input array errors in the view (L5.8 onwards)

To get the first validation error for an input array:

{{ $errors->first('input_array.*') }}

To check if there is an error within an input array:

@if($errors->has('input_array.*'))
    <h1>There is an error in your input array</h1>
    <ul>
       @foreach($errors->get('input_array.*') as $errors)
           @foreach($errors as $error)
               <li>{{ $error }}</li>
           @endforeach
       @endforeach
    </ul>
@endif

Other examples:

@error('input_array.*')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

From 5.8^ documentation

Working with error messages

If you are validating an array form field, you may retrieve all of the messages for each of the array elements using the * character:

foreach ($errors->get('attachments.*') as $message) {
    //
}

Hope it helps!

Solution 2:[2]

The errors are collected by name property, not id, and Laravel's default MessageBag variable is $messages, not $errors:

if( $messages->has('box-nickname') ) { echo ' has-error'; }

http://laravel.com/docs/4.2/validation#working-with-error-messages

Solution 3:[3]

$errors is correct, but you should be checking for box-nickname. As you can see you will run into the issue of not being able to identify what box is what because of the generic name. I think the easiest way to to give each input a unique name (eg. box-1, box-2)and do a for loop on the server side to retrieve inputs that start with box-.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 David Nguyen