21

Default solution is trivial:

@if (count($errors) > 0)
<ul id="login-validation-errors" class="validation-errors">
    @foreach ($errors->all() as $error)
    <li class="validation-error-item">{{ $error }}</li>
    @endforeach
</ul>
@endif

and I can include errors.blade.php anywhere.

Is there any way to extract each element and display it next to input field that holds the value that failed?

I assume that would require me to define a lot of conditional if statements next to each input, right?

How to sort this problem? Could you give me any examples?

Thanks.

4 Answers 4

30

You can use something like this :

<div class="form-group {{ $errors->has('name') ? 'has-error' : ''}}">
    <label for="name" class="col-sm-3 control-label">Name: </label>
    <div class="col-sm-6">
        <input class="form-control" required="required" name="name" type="text" id="name">
        {!! $errors->first('name', '<p class="help-block">:message</p>') !!}
    </div>
</div>
Sign up to request clarification or add additional context in comments.

4 Comments

Works perfectly. Thanks!
Lets say the text input name has multiple errors like 'name' => 'required|min:20', then how do we show multiple error lines here?
@mapmalith These two errors are not possible at the same time
it is possible. foreach ($errors->get('email') as $message) { // }
5

@Zorx has given a right solution. But what if there are multiple errors and you want to display all of them at once.

According to the documentation you could use:

Retrieving All Error Messages For A Field

foreach ($errors->get('email') as $message) {
//
}

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) {
//
}

Retrieving All Error Messages For All Fields

foreach ($errors->all() as $message) {
    //
}

Comments

4

Laravel Introduced The @error Directive in version 6 and 7

<input id="title" type="text" name="title" class="@error('title') is-invalid @enderror">

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

documentation

Comments

0

Validation individual error message and input border with red color using bootstrap classes and Laravel's $errors directive

Input field with red border color

<input type="text" name="fullName" class="form-control {{($errors->first('fullName') ? 'is-invalid' : '')}}" value="{{old('fullName');}}">
//Or
<input type="text" name="fullName" class="form-control @error('fullName') is-invalid @enderror" value="{{old('fullName');}}">

Individual validation error message

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.