Laravel 5.2 验证错误未出现

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34888232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:04:10  来源:igfitidea点击:

Laravel 5.2 validation errors not appearing

phpvalidationlaravellaravel-5laravel-5.2

提问by user1072337

I am trying to get validation errors to show up in Laravel.

我试图让验证错误显示在 Laravel 中。

I have a UserController set up like so:

我有一个 UserController 设置如下:

<?php

namespace App\Http\Controllers;

use App\User;
use App\Http\Controllers\Controller;
//Use Request;
Use Flash;
Use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return Response
     */
    public function showProfile($id)
    {
        return view('user.profile', ['user' => User::findOrFail($id)]);
    }

    public function store(Request $request) {
        $this->validate($request, [
            'email' => 'required|unique:users|email|max:255',
        ]);

        if($this) {

        $input = Request::all();

        User::create($input);

        return redirect('/');

        }
        else {

            return redirect('/')->withErrors($validator);
        }
    }
}

In my view (layout.blade.php), I have included:

在我看来(layout.blade.php),我已经包括:

@if (count($errors) > 0)
@foreach ($errors->all() as $error)
   {{!! $errors !!}}
@endforeach
@endif

To account for the route, I have:

为了说明路线,我有:

Route::group(['middleware' => ['web']], function () {
    Route::get('/', function (){
        return view('home');
    });
});

Unfortunately, when I enter "bad" data that shouldn't be verified, I am not seeing any error (but it is not being stored in the db, so there's that).

不幸的是,当我输入不应验证的“坏”数据时,我没有看到任何错误(但它没有存储在数据库中,所以就是这样)。

One other note, when the blade template is rendered, I am seeing an extra "}" bracket, which I'm not sure why that is there.

另一个注意事项是,当渲染刀片模板时,我看到一个额外的“}”括号,我不确定为什么会出现这种情况。

回答by Mirza Vu

In laravel version 5.2.41, the middleware web is thrown out.

在 laravel 5.2.41 版本中,中间件 web 被抛弃了。

Means adding the routes inside Route::group(['middleware' => ['web']], function () {will make the validation not work.

意味着在里面添加路由Route::group(['middleware' => ['web']], function () {会使验证不起作用。

回答by Logan Bailey

There are a couple things wrong or that can be improved here. The store method on the UserController has a lot of weird issues. $thiswill always be true because objects are true in php. Also, you pass in $validatorinto withErrorswhich doesn't make sense because there's no variable validator.

有几件事是错误的,或者可以在这里改进。UserController 上的 store 方法有很多奇怪的问题。$this将始终为真,因为对象在 php 中为真。此外,您传递$validatorwithErrors其中没有任何意义,因为没有变量validator

public function store(Request $request) {
    $this->validate($request, [
        'email' => 'required|unique:users|email|max:255',
    ]);

    User::create(Request::all());
    return redirect('/');
}

The validatemethod will throw an Illuminate\Foundation\Validation\ValidationExceptionif there is a validation error. This exception should be listed in the $dontReportinstance variable in App\Exceptions\Handleras seen below:

如果存在验证错误,该validate方法将抛出一个Illuminate\Foundation\Validation\ValidationException。此异常应列在$dontReport实例变量中App\Exceptions\Handler,如下所示:

protected $dontReport = [
    AuthorizationException::class,
    HttpException::class,
    ModelNotFoundException::class,
    ValidationException::class,
];

If you have changed these values, removed, or modified the ValidatesRequesttrait you may have broken this functionality.

如果您更改了这些值、删除或修改了ValidatesRequest特征,则您可能破坏了此功能。

Your error reporting code is not correct either:

您的错误报告代码也不正确:

@foreach ($errors->all() as $error)
   {!! $errors->first() !!}
@endforeach

There are 3 changes here. First I removed the outer errors size check, this doesn't really get you anything. Next, I fixed your extra }error, the syntax for un-escaping data is {!! $errors->first() !!}. Lastly, I called ->first()this returns the first error associated with that particular field.

这里有3个变化。首先,我删除了外部错误大小检查,这并没有真正为您提供任何帮助。接下来,我修复了您的额外}错误,非转义数据的语法是{!! $errors->first() !!}. 最后,我称之为->first()返回与该特定字段关联的第一个错误。

I think it's important to note that the validation exception will create a redirect response to the previous page. The logic for determining the previous page can be found in Illuminate\Routing\UrlGenerator::previous().

我认为重要的是要注意验证异常将创建到上一页的重定向响应。可以在 中找到确定上一页的逻辑Illuminate\Routing\UrlGenerator::previous()

回答by Chris

The errors block should be:

错误块应该是:

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <ul>
        @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
        </ul>
    </div>
@endif

Assuming you're using Bootstrap for the alerts.

假设您使用 Bootstrap 来发送警报。

You also don't have $validatordefined. You need to do something like this:

你也没有$validator定义。你需要做这样的事情:

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

Instead of $this->validate().

而不是$this->validate().

That should do it.

那应该这样做。

回答by Musthafa Ma

@if(count(($errors->all()) > 0))
@foreach($errors->all() as $error)
    <div class="alert alert-danger">
        {{$error}}
    </div>
@endforeach
@endif