Laravel验证器抛出一个异常,而不是重定向回


Laravel validator throws an exception instead of redirecting back

升级到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.
    }
}

但不知何故,当我输入未验证的数据时,它不会将我重定向回上一页,也不会将一些消息闪烁到会话,但它会触发一个异常,并给我一个500错误的页面。

这是我遇到的例外。我在文档中读到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

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

更新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,
];

我还建议您阅读如何迁移到laravel 5.2的文档,因为其中有一些突破性的更改。例如,ValidatesRequests特性抛出Illuminate'Foundation'Validation'ValidationException代替Illuminate'Http'Exception'HttpResponseException

如何从Laravel 5.1迁移到5.2 的文档

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

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

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

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

对于laravel 5.2,我必须添加以下行:

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

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

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

添加此行:

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

在这个之后:

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

App'Exceptions'Handler.php中,我做到了,并在使用FormRequest验证时返回了预期的验证错误。

请看我在这里的评论:@ratatatKE对github 的评论

可能会节省一些时间,另一个问题是您在视图中调用validator->validate(),而不是在控制器中

我在视图中调用,因为我有一个延迟加载组件,它在视图上触发

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

这个答案对我有效。

覆盖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);
}

答案如下:https://laracasts.com/discuss/channels/laravel/whoops-20-laravel-52