95

How can I display the validation message in the view that is being redirected in Laravel ?

Here is my function in a Controller

public function registeruser()
{
    $firstname = Input::get('firstname');
    $lastname = Input::get('lastname');
    $data  =  Input::except(array('_token')) ;
    $rule  =  array(
                'firstname'       => 'required',
                'lastname'         => 'required',
                   ) ;
    $validator = Validator::make($data,$rule);
    if ($validator->fails())
    {
    $messages = $validator->messages();
    return Redirect::to('/')->with('message', 'Register Failed');
    }
    else
    {
    DB::insert('insert into user (firstname, lastname) values (?, ?)',
                                array($firstname, $lastname));
    return Redirect::to('/')->with('message', 'Register Success');
    }
    }

I know the below given code is a bad try, But how can I fix it and what am I missing

@if($errors->has())
    @foreach ($errors->all() as $error)
        <div>{{ $error }}</div>
    @endforeach
@endif

Update : And how do I display the error messages near to the particular fields

3
  • 4
    You have to return the error messages, something like return Redirect::to('/')->withErrors($validator);
    – Vucko
    Nov 4, 2014 at 10:39
  • Thanks, it helped me
    – SA__
    Nov 4, 2014 at 11:23
  • @SA__ How you holded the typed value in each field after the validation redirect ?
    – user5621153
    Mar 15, 2016 at 12:57

15 Answers 15

196

Laravel 4

When the validation fails return back with the validation errors.

if($validator->fails()) {
    return Redirect::back()->withErrors($validator);
}

You can catch the error on your view using

@if($errors->any())
    {{ implode('', $errors->all('<div>:message</div>')) }}
@endif

UPDATE

To display error under each field you can do like this.

<input type="text" name="firstname">
@if($errors->has('firstname'))
    <div class="error">{{ $errors->first('firstname') }}</div>
@endif

For better display style with css.

You can refer to the docs here.

UPDATE 2

To display all errors at once

@if($errors->any())
    {!! implode('', $errors->all('<div>:message</div>')) !!}
@endif

To display error under each field.

@error('firstname')
    <div class="error">{{ $message }}</div>
@enderror
4
  • <input type="text" name="firstname"> how can i hold the typed value after validation ?
    – user5621153
    Mar 15, 2016 at 12:44
  • 1
    <input type="text" name="firstname" value="{{ old('firstname') }}"> or use form helper, it will automatically hold the value after validation error. Mar 17, 2016 at 12:00
  • 1
    Note that $errors->first('firstname') will only display the first message for the given field. You may have multiple errors; get them as an array for looping over like this: $errors->get('firstname')
    – Jason
    Mar 22, 2016 at 16:25
  • 1
    For people using bootstrap, here's your code snippet: @if($errors->any()) {!! implode('', $errors->all('<div class="alert alert-danger" role="alert">:message</div>')) !!} @endif
    – phoenix
    Apr 25, 2020 at 17:49
34

If you want to load the view from the same controller you are on:

if ($validator->fails()) {
    return self::index($request)->withErrors($validator->errors());
}

And if you want to quickly display all errors but have a bit more control:

 @if ($errors->any())
     @foreach ($errors->all() as $error)
         <div>{{$error}}</div>
     @endforeach
 @endif
11
@if ($errors->has('category'))
    <span class="error">{{ $errors->first('category') }}</span>
@endif
2
  • 2
    Please provide some details. Apr 8, 2015 at 7:27
  • 3
    Please provide additional detail in your answer to summaries what your code does.
    – Popeye
    Apr 8, 2015 at 7:54
7

A New Laravel Blade Error Directive comes to Laravel 5.8.13

// Before
@if ($errors->has('email'))
    <span>{{ $errors->first('email') }}</span>
@endif

// After:
@error('email')
    <span>{{ $message }}</span>
@enderror
7

to Make it look nice you can use little bootstrap help

@if(count($errors) > 0 )
<div class="alert alert-danger alert-dismissible fade show" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
    <ul class="p-0 m-0" style="list-style: none;">
        @foreach($errors->all() as $error)
        <li>{{$error}}</li>
        @endforeach
    </ul>
</div>
@endif
5
$validator = Validator::make($request->all(), [ 'email' => 'required|email', 'password' => 'required', ]);

if ($validator->fails()) { return $validator->errors(); }
1
  • Great you are helping, can you please explain for the less experienced fellows why and how your code solves the problem. To make the post more concise and readable use the proper formatting stackoverflow suggests: stackoverflow.com/editing-help
    – leopold
    Dec 1, 2019 at 15:38
5

You can use like below to print with html tags :

@if($errors->any())
    {!! implode('', $errors->all('<div>:message</div>')) !!}
@endif
2
@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
1
  • Please explain your answer. For example, why does this work ? Aug 5, 2022 at 4:00
1

Below input field I include additional view:

@include('input-errors', ['inputName' => 'inputName']) #For your case it would be 'email'

input-errors.blade.php

@foreach ($errors->get($inputName) as $message)
    <span class="input-error">{{ $message }}</span>
@endforeach

CSS - adds red color to the message.

.input-error {
    color: #ff5555;
}
1

Retrieving All Error Messages For All Fields

To retrieve an array of all messages for all fields, use the all method:

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

Laravel 9, https://laravel.com/docs/9.x/validation#retrieving-all-error-messages-for-all-fields

1
  • 1
    Welcome to Stackoverflow, it's nice to see a good first answer here, I upvoted your answer but please consider adding a link to the api documentation for this specific method and note which version of Laravel you're using.
    – Mike
    Nov 11, 2022 at 11:33
0
{!! Form::text('firstname', null !!}

@if($errors->has('firstname')) 
    {{ $errors->first('firstname') }} 
@endif
1
  • 3
    I think you should explain why you suggest this solution. It tells nothing as it is. Jun 19, 2019 at 14:22
0

This is also good way to accomplish task.

@if($errors->any())
  {!! implode('', $errors->all('<div class="alert alert-danger">:message</div>')) !!}
@endif

We can format tag as per requirements.

0

In case of using toastr use the following to show the error with floating message

@if($errors->any()) 
     <script type="text/javascript">
         toastr.error({{ implode(' ', $errors->all()) }});
    </script> 
@endif
0

If you are also using Laravel 8 and Bootstrap 5, you can display the errors neatly with alerts doing it like this:

@if($errors->any())
    <div class="alert alert-danger alert-dismissible">
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        <strong>
            {!! implode('<br/>', $errors->all('<span>:message</span>')) !!}
        </strong>
    </div>
@endif
-4

Move all that in kernel.php if just the above method didn't work for you remember you have to move all those lines in kernel.php in addition to the above solution

let me first display the way it is there in the file already..

protected $middleware = [

    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'api' => [
        'throttle:60,1',
    ],
];

now what you have to do is

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
     \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
];

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [

    ],

    'api' => [
        'throttle:60,1',
    ],
];

i.e.;

enter image description here

1
  • Doing this would make all those middlewares active for all of your current routes, instead just add the "web" middleware group to your routes. Like so Route::get('/home', 'controller@home')->middleware('web'); or add it into your controllers __construct method like so: $this->middleware('web'); If you are running a recent version of laravel, the 'web' middleware group is automatically applied to your routes/web.php file by the RouteServiceProvider. Dec 16, 2019 at 23:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.