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

时间:2016-01-05 11:38:50

标签: php validation laravel laravel-5 php-5.6

升级到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是new而不是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

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

7 个答案:

答案 0 :(得分:5)

更新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

Documentation how to migrate from Laravel 5.1 to 5.2

答案 1 :(得分:3)

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

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

出于我的目的,我在 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's comments on github

答案 4 :(得分:0)

对于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;

答案 5 :(得分:0)

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

我之所以在视图中进行调用是因为我有一个在视图上触发的延迟加载组件

答案 6 :(得分:-4)

升级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

相关问题