laravel 验证内容类型:应用程序/json 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31699400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
laravel validate Content-Type: application/json request
提问by Sudipta Dhara
in laravel 5 i made a new request named ApiRequest
.
在 Laravel 5 中,我提出了一个名为ApiRequest
.
class ApiRequest extends Request
{
public function authorize() {
return $this->isJson();
}
public function rules()
{
return [
//
];
}
}
As you can see i am accepting only json data. And i am receiving the json in controller like this
如您所见,我只接受 json 数据。我正在像这样在控制器中接收 json
public function postDoitApi(ApiRequest $payload) {
$inputJson = json_decode($payload->getContent());
$name = $inputJson->name;
}
Which is working fine. I am getting data in $name
. But now i need to validate the input json.
I need to set validation rule in ApiRequest
for the name
key like this
哪个工作正常。我正在获取数据$name
。但现在我需要验证输入 json。我需要ApiRequest
为这样的name
密钥设置验证规则
public function rules()
{
return [
'name' => 'required|min:6'
];
}
Help me to do this. Thanks.
帮我做这件事。谢谢。
采纳答案by Emeka Mbah
You could use a validator method instead of rules method:
您可以使用验证器方法而不是规则方法:
class ApiRequest extends Request
{
public function authorize() {
return $this->isJson();
}
public function validator(){
//$data = \Request::instance()->getContent();
$data = json_decode($this->instance()->getContent());
return \Validator::make($data, [
'name' => 'required|min:6'
], $this->messages(), $this->attributes());
}
//what happens if validation fails
public function validate(){
$instance = $this->getValidatorInstance();
if($this->passesAuthorization()){
$this->failedAuthorization();
}elseif(!$instance->passes()){
$this->failedValidation($instance);
}elseif( $instance->passes()){
if($this->ajax())
throw new HttpResponseException(response()->json(['success' => true]));
}
}
}
回答by Kestutis
Laravel validates AJAX requests the same way. Just make sure you're setting one of these request headers on your request:
Laravel 以同样的方式验证 AJAX 请求。只需确保您在请求中设置了以下请求标头之一:
'Accept': 'application/json'
'Accept': 'application/json'
'X-Requested-With': 'XMLHttpRequest'
'X-Requested-With': 'XMLHttpRequest'
回答by user4621032
return $inputJson->toArray();
and then pass to validator
然后传递给验证器
$name = ['name'=>'er'];
$rules = array('name' => 'required|min:4');
$validation = Validator::make($name,$rules);
回答by pinkal vansia
you can put following function in your ApiRequest
form request.
您可以在ApiRequest
表单请求中添加以下功能。
public function validator(){
return \Validator::make(json_decode($this->getContent(),true), $this->rules(), $this->messages(), $this->attributes());
}