我正在使用Laravel 5.1构建RESTful API - 当发出post请求时,我验证输入,如果输入无效,我抛出异常。
当前回应样本:
{
"message": "{\"email\":[\"The email field is required.\"]}",
"status_code": 400
}
如何让我的回复看起来像这样:
{
"message": {
"email": "The email field is required."
},
"status_code": 400
}
以下是我抛出异常的方法:
$validator = Validator::make($this->request->all(), $this->rules());
if ($validator->fails()) {
throw new ValidationFailedException($validator->errors());
}
答案 0 :(得分:3)
我认为在laravel中验证表单的最佳方法是使用Form Request Validation。您可以覆盖namespace App\Http\Requests;
Illuminate\Foundation\Http\FormRequest;
abstract class Request extends FormRequest
{
public function response(array $errors)
{
return $this->respond([
'status_code' => 400 ,
'message' => array_map(function($errors){
foreach($errors as $key=>$value){
return $value;
}
},$errors)
]);
}
/**
* Return the response
*/
public function respond($data , $headers=[] ){
return \Response::json($data);
}
}
类中的响应方法。
的 Request.php 强>
const uint32_t val_int = (tab[0] << 24) | (tab[1] << 16) | (tab[2] << 8) | tab[3];
答案 1 :(得分:1)
你可以试试这个:
$messages = [
'email.required' => 'The :attribute field is required.',
];
$validator = Validator::make($input, $rules, $messages);
答案 2 :(得分:0)
这是我使用的课程:
<?php
namespace App;
class Hack
{
public static function provokeValidationException($field_messages){
$rules = [];
$messages = [];
foreach($field_messages as $field=>$message){
$rules[$field] = 'required';
$messages[$field. '.required'] = $message;
}
$validator = \Validator::make([], $rules, $messages);
if ($validator->fails()) {
throw new \Illuminate\Validation\ValidationException($validator);
}
}
}
然后,只要我需要显示自定义错误,我就会这样做:
\App\Hack::provokeValidationException(array(
'fieldname'=>'message to display',
'fieldname2'=>'message2 to display',
));
答案 3 :(得分:0)
我遇到了同样的问题,并且通过解码return (400, json_decode($exception->getMessage()));
响应来解决了该问题
{{1}}