Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AdamEsterle's avatar

$error->has() for ANY errors in input array

I want to check, on my view, if there are any errors.

Normally: $errors->has(name-of-field) Or with an array: $errors->has(array.index)

How do I check if there was an error for ANY of my input arrays?

I want so display an error if $error->has('user.0') || $error->has('user.1') || ... But I do not know how many users will be validated, I just want to display the error if user.any has an error

I tried: $errors->has('user.*') , but that did not work

Any ideas?

0 likes
16 replies
Thijmen's avatar

Best guess: count($errors->get('user'))?

AdamEsterle's avatar

@Snapey I cannot do that as I have other fields on the form

@Thijmen $errors->get('user'); does not work so neither would count() around it

Snapey's avatar

dd $errors and see what it looks like. You should be able to simply check for the presence of the user array?

Guardian's avatar

@AdamEsterle ,

Maybe this could be an idea:

@if($errors->has())
   @foreach ($errors->all() as $error)
    // Do Some custom validation here to check if the "user.x" is present?
      <div>{{ $error }}</div>
  @endforeach
@endif 

Does not feel like the cleanest solution, but should do the trick...

alainbelez's avatar

here's what im using before:

{!! $errors->first('name', '<span class="help-block">:message</span>') !!}

so it's kinda weird that has doesn't work

1 like
AdamEsterle's avatar
AdamEsterle
OP
Best Answer
Level 30

Here is what I am doing so that the view can be as clean as possible.

I am running a check after the validation to see if there exists an error on the members.. If there is, I add the error with the name of 'members'. This way, on my view side, I can keep it clean with $error->has('members') etc. I can run the regular expression here to check for members.

public function getValidatorInstance()
    {
        $validator = parent::getValidatorInstance();

        $validator->after(function () use ($validator) {
            if ($error = $this->getIndividualMemberError($validator)) {
                $validator->errors()->add('members', $error);
            }
        });

        return $validator;
    }

private function getIndividualMemberError($validator)
    {
        $individualError = collect($validator->messages())->first(function ($key, $value) {
            return preg_match('/members\./', $key);
        });

        return is_null($individualError) ? false : collect($individualError)->first();
    }

If the MessagesBag->has() could take a regular expression, that would make this not needed

Kryptonit3's avatar

I know this is old but I have found a solution that works for me for my dynamically generated inputs. (http://formvalidation.io/examples/adding-dynamic-field/)

image

    public function rules()
    {
        return [
            'active' => 'boolean',
            'name' => 'required',
            'notes' => '',
            'identifiers.*.name' => 'required|numeric',
            'identifiers.*.value' => 'required|numeric',
        ];
    }
@if($errors->has('*'))
                        <?php $count = 1; ?>
                        @foreach($errors->all() as $error)
                            @if($errors->has('identifiers.' . $count . '.*'))
                                <div data-identifier-index="{{ $count }}">
                                    <div class="row mb-2 newIdentifier">
                                        <div class="col-5">
                                            <input type="text" class="form-control {{ $errors->has('identifiers.'.$count.'.name') ? 'is-invalid' : '' }}" name="identifiers[{{ $count }}][name]" value="{{ old('identifiers.'.$count.'.name') }}" placeholder="Name: CMAC, S/N">
                                            @if($errors->has('identifiers.'.$count.'.name'))
                                                <div class="invalid-feedback">
                                                    <p class="m-0">
                                                        {{ $errors->first('identifiers.'.$count.'.name') }}
                                                    </p>
                                                </div>
                                            @endif
                                        </div>
                                        <div class="col-5">
                                            <input type="text" class="form-control {{ $errors->has('identifiers.'.$count.'.value') ? 'is-invalid' : '' }}" name="identifiers[{{ $count }}][value]" value="{{ old('identifiers.'.$count.'.value') }}" placeholder="Value">
                                            @if($errors->has('identifiers.'.$count.'.value'))
                                                <div class="invalid-feedback">
                                                    <p class="m-0">
                                                        {{ $errors->first('identifiers.'.$count.'.value') }}
                                                    </p>
                                                </div>
                                            @endif
                                        </div>
                                        <div class="col">
                                            <button class="btn btn-sm btn-danger removeButton mt-1">Remove</button>
                                        </div>
                                    </div>
                                </div>
                                <?php $count++ ?>
                            @endif
                        @endforeach
                    @endif 
2 likes
paewebservices's avatar

Got it down to one line for use in blade:

@if ( count(preg_grep ('/^affiliation./', array_keys($errors->messages())))>0 ) ... @endif

Here, "affiliation" is the name of a group of checkboxes (the array that may have an error.) So I'm looking for "affiliation." in the keys of the array returned by $errors->messages().

So count() > 0 will eval to true if there was an error within the affiliation array.

EDIT:

ZeyadMounir's answer does the same thing with less code.

Rahmah's avatar

There is a crazy:D you just need to add this:

class="form-control @if($errors->insert->first('username')) is-invalid @endif"

Haitham Al's avatar

Hi, I am really benefit from this discussion. I have been struggled for several days trying to find a solution for a simple problem. Now after gathering all knowledge required to break this dilemma, I would like to share with you the ultimate evolution of this code :)

First, you need to set your validation:

    $request->validate([
        'discountPrice' => 'array',
        'discountPrice.*' => 'required']);

Second, in your form if you use Laravel collective package you will need only to do the following:

{!! Form::text('discountPrice[]', '', ['class' => 'form-control'.( $errors->first('discountPrice.'.$loop->index) ? ' is-invalid' : '' ), 'placeholder' => '0']) !!}

it's important to use (first) to capture the correct input array and notice the using of $loop to get the index key of the array.

and that the end of the hassle around.

underdpt's avatar

It's been a long time, but this is how I check array validation errors with dotted notation against the name of the input (with array notation) with dynamic names (for example, on a generic blade component for text inputs):

    {{-- $name is the input name --}}
    @if ($errors->has($name))
        <small class="text-danger">{{ $errors->first($name) }}</small>
    @elseif ($errors->has($errorKey = str_replace(['[', ']'], ['.', ''], $name)))
        {{-- $errorKey is the input name changed to dot notation --}}
        <small class="text-danger">{{ $errors->first($errorKey) }}</small>
    @endif 
1 like

Please or to participate in this conversation.