Laravel 中的验证错误 - 验证失败后未填充 $errors 数组

Validation error in Laravel - $errors array does not get populated after the validation failure

我 运行 遇到了一个关于 Laravel 5.2 验证的 st运行ge 问题。我在 Whosebug 上查看了以下问题,但其中 none 似乎适用于我的情况:

Laravel validation not showing errors

问题是,在将 Card 对象保存到数据库之前,我正在尝试验证 title 字段。当我按预期提交带有空 title 字段的表单时,它没有通过验证。但是,$errors 数组不会在上述验证失败时填充。谁能解释一下这段代码哪里出了问题?

/////////////////////// CONTROLLER /////////////////////
public function create(Request $request)
{
    $this->validate($request, [
        'title' => 'required|min:10'
    ]);

    Card::create($request->all());
    return back();
}
///////////////////////// VIEW /////////////////////////
// Show errors, if any. (never gets triggered)
@if(count($errors))
    <ul>
        @foreach($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
    </ul>
@endif
<form method="POST" action="/cards">
    {{ csrf_field() }}

    <div class="form-group">
        // The textarea does not get populated with the 'old' value as well
        <textarea class="form-control" name="title">{{ old('title') }}</textarea>
    </div>

    <div class="form-group">
        <button class="btn btn-primary" type="submit">Add Card</button>
    </div>
</form>

我猜你必须将 if 子句设置为 @if(count($errors) > 0)

在您的控制器中,尝试添加 $validator->fails() 语句,并使用 ->withErrors() 来 return 模板中的任何错误。

public function create(Request $request)
{
    $validator = Validator::make($request->all(), [
        'title' => 'required|min:10'
    ]);

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

    Card::create($request->all());
    return back();
}

如果您 运行宁 Laravel 5.2.27 及以上,则不再需要使用网络中间件组。事实上,你不应该将它添加到你的路由中,因为它现在默认自动应用。

如果您打开 app/Http/RouteServiceProvider.php 文件,您将看到这段代码:

protected function mapWebRoutes(Router $router)
{
    $router->group([
        'namespace' => $this->namespace, 'middleware' => 'web',
    ], function ($router) {
        require app_path('Http/routes.php');
    });
}

来源:https://github.com/laravel/laravel/blob/master/app/Providers/RouteServiceProvider.php#L53

如您所见,它会自动为您应用网络中间件。如果您尝试在您的路由文件中再次(多次)应用它,您将 运行 遇到像您当前面临的奇怪问题。

为了找出您 运行ning 的 Laravel 版本,运行 此命令:php artisan --version