Evaldas Butkus
Evaldas Butkus

Reputation: 665

Laravel 5.0 separated error messages for form validation

I did define my validator rules like this:

foreach ($this->request->get('name') as $key => $val) {
            $rules['name.'.$key]    = 'required';
            $rules['phone.'.$key]   = 'required';
            $rules['comment.'.$key] = 'required';
        }
return $rules;

The problem is that i can't loop through, for example, name errors. All I can do is looping through them like this:

@foreach ($errors->all() as $error)
    {{ $error }}
@endforeach

I have 3 different input fields. How can I write out the errors separately beneath each input box?

Upvotes: 2

Views: 1098

Answers (2)

Mark
Mark

Reputation: 1

Your update solution works but if your validation returns more than one message it only shows the first one. If you want to give all the error information to the user you should do this:

@if ($errors->has('name'))
  @foreach($errors->get('name') as $error)
    {!! $error !!}
  @endforeach
@endif

I recommend to put this into a partial blade and @include it for each input you need just passing the $errors object and the name of the input.

Upvotes: 0

OskarD90
OskarD90

Reputation: 633

Laravel does not offer the functionality to display the error messages individually for every field. You would have to figure out a manual way of doing this if you want the feature in your application.

Update

I don't know if this particular thing existed in earlier versions of Laravel, I sure never heard of it, but as of Laravel 5.2 you can display form validation error messages separately. Here is a good video that demonstrates the functionality on Laracasts.

Using your example, here is what the code would look like (Without any styling):

<input name='name'>
@if ($errors->has('name'))
    {{ $errors->first('name') }}
@endif

Upvotes: 1

Related Questions