请求数据失败Laravel验证,即使它不应该

时间:2016-11-20 17:01:04

标签: php laravel

我收到以下错误:

  

给定数据未通过验证。 /home/vagrant/Code/laravel/ptm/vendor/laravel/framework/src/Illuminate/Foundation/Validation/ValidatesRequests.php#89

当我查看$data时,它已经填满了:

array:1 [
  "{"_token":"Z5fv3XpoNwoMdJPRP16I09bZeX7Pb6raH30K8n3b","name":"test","id":"","email":"test@example_com","password":"testing"}"
]

以下是代码:

public function create(Request $request)
{

        $data = $request->all();            

        $this->validate($request, ['name' => 'required',
                            'email' => 'required',
                            'password' => 'required'
                        ]);

  try
  {
    $this->user->create($request);
  }
  catch (Exception $e)
  {
    return json_encode(array('success' => false, 'message' => 'Something went wrong, please try again later.'));
  }

  return json_encode(array('success' => true, 'message' => 'User successfully saved!'));
}

2 个答案:

答案 0 :(得分:0)

很明显,validate()方法正在抛出异常。如果您不想抛出异常,请更新您的App\Exceptions\Handler课程并将ValidationException添加到$dontReport数组中:

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        \Illuminate\Auth\AuthenticationException::class,
        \Illuminate\Auth\Access\AuthorizationException::class,
        \Symfony\Component\HttpKernel\Exception\HttpException::class,
        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
        \Illuminate\Session\TokenMismatchException::class,
        \Illuminate\Validation\ValidationException::class, // <= Here
    ];

了解更多:
Documentation how to migrate from Laravel 5.1 to 5.2

或者您可以保持原样,并在新的catch块中处理异常:

public function create(Request $request)
{
    try {
        $this->validate($request, [
            'name'     => 'required',
            'email'    => 'required',
            'password' => 'required'
        ]);

        $this->user->create($request);
    } catch (ValidationException $e) {
        return response()->json([
            'success' => false, 
            'message' => 'There were validation errors.',
        ], 400);
    } catch (Exception $e) {
        return response()->json([
            'success' => false, 
            'message' => 'Something went wrong, please try again later.'
        ], 400);
    }

    return response()->json([
        'success' => true, 
        'message' => 'User successfully saved!'
    ], 201);
}

答案 1 :(得分:-1)

您可以在变量上检查刀片模板中是否有正确的大小写。例如'name','email'和'password'区分大小写,变量的刀片模板大小写必须与控制器的变量大小写匹配。

相关问题