首页 文章

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

提问于
浏览
10

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

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

6 回答

  • 1

    更新 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 trait抛出 Illuminate\Foundation\Validation\ValidationException 而不是 Illuminate\Http\Exception\HttpResponseException

    Documentation how to migrate from Laravel 5.1 to 5.2

  • 0

    laravel docs中的示例 . 您可以使用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...
    }
    
  • -4

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

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

  • 5

    出于我的目的,我在 Laravel 5.3 中 Build 了一个完全基于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

  • 3

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

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

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

    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;
    
  • 0

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

相关问题