我收到以下错误:
给定数据未通过验证。 /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!'));
}
答案 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'区分大小写,变量的刀片模板大小写必须与控制器的变量大小写匹配。