[php] Displaying the Error Messages in Laravel after being Redirected from controller

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

This question is related to php laravel laravel-4 blade

The answer is


$validator = Validator::make($request->all(), [ 'email' => 'required|email', 'password' => 'required', ]);

if ($validator->fails()) { return $validator->errors(); }

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

@if ($errors->has('category'))
    <span class="error">{{ $errors->first('category') }}</span>
@endif

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


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.


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

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

{!! Form::text('firstname', null !!}

@if($errors->has('firstname')) 
    {{ $errors->first('firstname') }} 
@endif

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;
}

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to laravel-4

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration 'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel Can I do Model->where('id', ARRAY) multiple where conditions? how to fix stream_socket_enable_crypto(): SSL operation failed with code 1 Rollback one specific migration in Laravel How can I resolve "Your requirements could not be resolved to an installable set of packages" error? Define the selected option with the old input in Laravel / Blade Redirect to external URL with return in laravel laravel the requested url was not found on this server

Examples related to blade

How to access URL segment(s) in blade in Laravel 5? Lumen: get URL parameter in a Blade view Laravel: How do I parse this json data in view blade? Switch in Laravel 5 - Blade Laravel-5 how to populate select box from database with id value and name value Laravel 5: Display HTML with Blade Define the selected option with the old input in Laravel / Blade Laravel 5 call a model function in a blade view Displaying the Error Messages in Laravel after being Redirected from controller How to include a sub-view in Blade templates?