从控制器重定向后在 Laravel 显示错误消息

如何在 Laravel 重定向的视图中显示验证消息?

这是我在控制器中的函数

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

我知道下面给出的代码是一个糟糕的尝试,但我怎样才能修复它和什么是 我失手了

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

更新: 以及如何在特定字段附近显示错误消息

381676 次浏览

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
@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

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

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

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


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

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.

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

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

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

You can use like below to print with html tags :

@if($errors->any())
{!! implode('', $errors->all('<div>:message</div>')) !!}
@endif
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>\{\{ $error }}</li>
@endforeach
</ul>
</div>
@endif

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