为什么错误消息没有出现在 Laravel 视图中?

Why error messages doesn't Appear in Laravel views?

我想在存储角色时使用自定义请求将自定义验证消息传递到我的视图。

我创建了一个名为 StoreRoleRequest

的新请求
<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;
use Illuminate\Contracts\Validation\Validator;

class StoreRoleRequest extends Request
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name'   => 'required'
        ];
    }

    protected function formatErrors(Validator $validator)
    {
        return $validator->errors()->all();
    }

    public function messages()
    {
        return [
            'name.required' => 'the name of the Role is mandatory',
        ];
    }
}

然后将此自定义请求传递到 RoleController 中的我的存储函数,如下所示:

public function store(StoreRoleRequest $request)
{
    Role::create($request->all());
    return redirect(route('role.index'));
}

我有一个显示创建角色表单的视图,其中验证似乎正常工作但没有向我显示错误,即使我像这样将它们调用到视图中也是如此:

{!! Former::open()->action(route('role.store')) !!}
@if (count($errors->all()))
    <div class="alert alert-danger">
        @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
    </div>
@endif
{!! Former::text('name')->label('Groupe name')   !!}
{!! Former::text('display_name')->label('Displayed name')   !!}
{!! Former::text('description')->label('Description')   !!}

{!! Former::actions( Button::primary('Save')->submit(),
                    Button::warning('Clear')->reset()  ,
                    Button::danger('Close')->asLinkTo('#')->withAttributes(['data-dismiss' => 'modal'])
 )!!}
{!! Former::close() !!}

有谁知道为什么错误没有出现在视图中?我是在自定义请求中循环播放内容吗?

编辑

注意:即使在登录和注册表单中,错误也不会再出现。

在这种情况下,我将指向 web ['middleware' => ['web'] 的中间件更改为:

Route::group(['middleware' => []], function () 
{
    // other routes
    Route::resource('role', 'RoleController');
});

我所有的错误都完美显示。

你找到这个问题的根本原因了吗?

尝试通过这种方式询问是否存在错误:

@if($errors->any())
    // Your code
    @foreach($errors->all() as $error)
        <li>{{ $error }}</li>
    @endforeach
    // More code
@endif

同时从请求中删除 formatErrors 函数...您不需要它...

函数messages()负责返回您的自定义消息...

此致。

在你的问题更新后,你有更新版本的 Laravel 应用程序(不要将它与 Laravel 框架混淆)。 要验证这一点,请打开文件 app/Providers/RouteServiceProvider.php 并验证方法 map 方法的内容是什么。如果它启动 mapWebRoutes,则意味着您有 5.2.27+ 自动应用 web 组中间件的应用程序。

如果自动应用 web 中间件,您 不应 routes.php 文件中应用 web 中间件,因为它会导致意外行为。

因此,如果您在 RouteServiceProvider class 中定义了 mapWebRoutes,那么您应该从 routes.php 中删除 web 中间件,或者您可以修改您的RouteServiceProvider class 不自动应用 web 组中间件。选择哪种解决方案取决于您。

仅供快速参考: