[英]How to add Content-Type application/json in this request
[英]laravel validate Content-Type: application/json request
在 laravel 5 中,我提出了一個名為ApiRequest
的新請求。
class ApiRequest extends Request
{
public function authorize() {
return $this->isJson();
}
public function rules()
{
return [
//
];
}
}
如您所見,我只接受 json 數據。 我正在像這樣在控制器中接收 json
public function postDoitApi(ApiRequest $payload) {
$inputJson = json_decode($payload->getContent());
$name = $inputJson->name;
}
哪個工作正常。 我在$name
獲取數據。 但現在我需要驗證輸入 json。 我需要在ApiRequest
為這樣的name
鍵設置驗證規則
public function rules()
{
return [
'name' => 'required|min:6'
];
}
幫我做這件事。 謝謝。
Laravel 以同樣的方式驗證 AJAX 請求。 只需確保您在請求中設置了以下請求標頭之一:
'Accept': 'application/json'
'X-Requested-With': 'XMLHttpRequest'
您可以使用驗證器方法而不是規則方法:
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]));
}
}
}
return $inputJson->toArray();
然后傳遞給驗證器
$name = ['name'=>'er'];
$rules = array('name' => 'required|min:4');
$validation = Validator::make($name,$rules);
您可以將以下功能放在您的ApiRequest
表單請求中。
public function validator(){
return \Validator::make(json_decode($this->getContent(),true), $this->rules(), $this->messages(), $this->attributes());
}
可以通過兩個步驟以干凈的方式驗證任何標頭:
prepareForValidation
方法中准備請求數據的頭部數據。public function prepareForValidation()
{
$this->merge([
"content_type" => $this->headers->get("Content-type"),
]);
}
application/json
。所以public function rules(): array
{
return [
"content_type" => "required|in:application/json",
];
}
完整示例如下所示:
/**
* Class LoginRequest
*
* @package App\Requests
*/
class LoginRequest extends FormRequest
{
public function prepareForValidation()
{
$this->merge([
"content_type" => $this->headers->get("Content-type"),
]);
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules(): array
{
return [
"content_type" => "required|in:application/json",
];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.