Laravel 验证器抛出异常而不是重定向回来

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34610845/
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 12:58:35  来源:igfitidea点击:

Laravel validator throws an exception instead of redirecting back

phpvalidationlaravellaravel-5php-5.6

提问by DB93

After I upgraded to Laravel 5.2 I encountered a problem with the laravel validator. When I want to validate data in a controller take for example this code.

升级到 Laravel 5.2 后,我遇到了 Laravel 验证器的问题。当我想验证控制器中的数据时,以这段代码为例。

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

class ContactController extends Controller
{
    public function storeContactRequest(Request $request)
    {
        $this->validate($request, [
            '_token' => 'required',
            'firstname' => 'required|string'
            'lastname' => 'required|string'
            'age' => 'required|integer',
            'message' => 'required|string'
        ]);

        // Here to store the message.
    }
}

But somehow when I enter unvalid data it will not redirect me back to the previous page and flash some messages to the session but it will trigger an exception and gives me a 500 error page back.

但不知何故,当我输入无效数据时,它不会将我重定向回上一页并将一些消息闪现到会话中,但它会触发异常并返回 500 错误页面。

This is the exception I get. I have read in the documentation that the ValidationException is new instead of the HttpResponseException but I don't know if it has anything to do with this.

这是我得到的例外。我在文档中读到 ValidationException 是新的而不是 HttpResponseException 但我不知道它是否与此有关。

[2016-01-05 11:49:49] production.ERROR: exception 'Illuminate\Foundation\Validation\ValidationException' with message 'The given data failed to pass validation.' in /home/vagrant/Code/twentyre-webshop/vendor/laravel/framework/src/Illuminate/Foundation/Validation/ValidatesRequests.php:70

And when I use a seperate request class it will just redirect back with the error messages. It seems to me only the validate method used in a controller is affected by this behaviour.

当我使用单独的请求类时,它只会重定向回错误消息。在我看来,只有控制器中使用的验证方法会受到这种行为的影响。

回答by xAoc

Update your App\Exceptions\Handlerclass

更新你的App\Exceptions\Handler课程

use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Validation\ValidationException;

/**
 * A list of the exception types that should not be reported.
 *
 * @var array
 */
protected $dontReport = [
    AuthorizationException::class,
    HttpException::class,
    ModelNotFoundException::class,
    ValidationException::class,
];

I also recommend you to read the docs how to migrate to laravel 5.2, because there were some breaking changes. For example this, ValidatesRequeststrait throws Illuminate\Foundation\Validation\ValidationExceptioninstead of Illuminate\Http\Exception\HttpResponseException

我还建议您阅读如何迁移到 Laravel 5.2 的文档,因为有一些重大更改。例如,ValidatesRequests特征抛出 Illuminate\Foundation\Validation\ValidationException而不是Illuminate\Http\Exception\HttpResponseException

Documentation how to migrate from Laravel 5.1 to 5.2

文档如何从 Laravel 5.1 迁移到 5.2

回答by Nickstery

Example from laraveldocs. You can use Validator facade, for custom validation fails behaviour

laravel文档中的示例。您可以使用 Validator 外观,用于自定义验证失败行为

public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    if ($validator->fails()) {
        return redirect('post/create')
                    ->withErrors($validator)
                    ->withInput();
    }

    // Store the blog post...
}

回答by Rav

This is how I handle it in Laravel 5.3 (by modifying Handler.php)

这就是我在 Laravel 5.3 中处理它的方式(通过修改Handler.php

https://stackoverflow.com/a/42852358/3107185

https://stackoverflow.com/a/42852358/3107185

回答by Moses Ndeda

For my purpose, I was bulding a fully API based application in Laravel 5.3which I had manually upgraded from Laravel 5.1. and I just needed Laravel to respond back with the validation errors that needed fixing on my FormRequest.

出于我的目的,我在Laravel 5.3构建了一个完全基于 API 的应用程序,这是我从 Laravel 5.1 手动升级的。我只需要 Laravel 回复需要在我的 FormRequest 上修复的验证错误。

Adding this line:

添加这一行:

elseif ($e instanceof ValidationException) 
 {
        return $this->convertValidationExceptionToResponse($e, $request);
 }

after this one:

在这之后:

    if ($e instanceof ModelNotFoundException) {
        $e = new NotFoundHttpException($e->getMessage(), $e);
    }

In App\Exceptions\Handler.phpdid the trick for me and returned expected validation errors when using FormRequest validation.

App\Exceptions\Handler.php使用 FormRequest 验证时,它对我有用并返回了预期的验证错误。

Please see my comments here: @ratatatKE's comments on github

请在此处查看我的评论:@ratatatKE 在 github 上的评论

回答by Eduardo Lemus

For laravel 5.2 I had to add this line:

对于laravel 5.2,我必须添加这一行:

    if ($e instanceof ValidationException) 
    {
         return redirect()->back()->withInput();
    }

In App\Exceptions\Handler.php,and the following headers:

在 App\Exceptions\Handler.php 中,以及以下标题:

    use Illuminate\Session\TokenMismatchException;
    use Illuminate\Database\Eloquent\ModelNotFoundException;
    use Symfony\Component\HttpKernel\Exception\HttpException;
    use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
    use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
    use Illuminate\Validation\ValidationException;
    use Illuminate\Auth\AuthenticationException;

回答by Robbie

I had the same problem when upgrading 4.2 to 5.3.

将 4.2 升级到 5.3 时,我遇到了同样的问题。

This answer worked for me.

这个答案对我有用。

Override the method in app/Exceptions/Handler.php

覆盖 app/Exceptions/Handler.php 中的方法

protected function convertExceptionToResponse(Exception $e)
{
    if (config('app.debug')) {
        $whoops = new \Whoops\Run;
        $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler);

        return response()->make(
            $whoops->handleException($e),
            method_exists($e, 'getStatusCode') ? $e->getStatusCode() : 500,
            method_exists($e, 'getHeaders') ? $e->getHeaders() : []
        );
    }

    return parent::convertExceptionToResponse($e);
}

Answer found here: https://laracasts.com/discuss/channels/laravel/whoops-20-laravel-52

答案在这里找到:https: //laracasts.com/discuss/channels/laravel/whoops-20-laravel-52