Displaying the Error Messages in Laravel after being Redirected from controller
Asked Answered
A

15

105

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

Aerie answered 4/11, 2014 at 10:27 Comment(2)
You have to return the error messages, something like return Redirect::to('/')->withErrors($validator);Superstar
@Aerie How you holded the typed value in each field after the validation redirect ?Galan
W
219

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
Walkout answered 4/11, 2014 at 11:4 Comment(4)
<input type="text" name="firstname"> how can i hold the typed value after validation ?Galan
<input type="text" name="firstname" value="{{ old('firstname') }}"> or use form helper, it will automatically hold the value after validation error.Walkout
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')Athlete
For people using bootstrap, here's your code snippet: @if($errors->any()) {!! implode('', $errors->all('<div class="alert alert-danger" role="alert">:message</div>')) !!} @endifGuinness
G
39

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
Grain answered 29/8, 2018 at 1:39 Comment(0)
R
11
@if ($errors->has('category'))
    <span class="error">{{ $errors->first('category') }}</span>
@endif
Rubel answered 8/4, 2015 at 7:6 Comment(2)
Please provide some details.Proteus
Please provide additional detail in your answer to summaries what your code does.Maud
P
8

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
Plaintive answered 12/8, 2019 at 7:57 Comment(0)
C
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
Countermove answered 25/10, 2019 at 7:8 Comment(0)
A
6
@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
Angiosperm answered 4/11, 2014 at 10:27 Comment(1)
Please explain your answer. For example, why does this work ?Duquette
F
5
$validator = Validator::make($request->all(), [ 'email' => 'required|email', 'password' => 'required', ]);

if ($validator->fails()) { return $validator->errors(); }
Foss answered 1/12, 2019 at 14:31 Comment(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-helpEverglades
J
5

You can use like below to print with html tags :

@if($errors->any())
    {!! implode('', $errors->all('<div>:message</div>')) !!}
@endif
Jerri answered 6/2, 2022 at 11:17 Comment(0)
C
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;
}
Cantle answered 6/2, 2021 at 14:50 Comment(0)
N
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

Nobelium answered 8/11, 2022 at 15:38 Comment(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.Decastyle
B
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.

Backspin answered 20/10, 2020 at 8:1 Comment(0)
R
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
Royden answered 25/4, 2021 at 7:20 Comment(0)
C
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
Chef answered 28/12, 2021 at 9:21 Comment(0)
E
-1
{!! Form::text('firstname', null !!}

@if($errors->has('firstname')) 
    {{ $errors->first('firstname') }} 
@endif
Erwin answered 19/6, 2019 at 11:4 Comment(1)
I think you should explain why you suggest this solution. It tells nothing as it is.Consistent
B
-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

Benefaction answered 3/4, 2016 at 13:37 Comment(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.Knee

© 2022 - 2024 — McMap. All rights reserved.