简体   繁体   English

laravel 验证内容类型:应用程序/json 请求

[英]laravel validate Content-Type: application/json request

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.如您所见,我只接受 json 数据。 And i am receiving the json in controller like this我正在像这样在控制器中接收 json

public function postDoitApi(ApiRequest $payload) {
        $inputJson = json_decode($payload->getContent()); 
        $name = $inputJson->name;
}

Which is working fine.哪个工作正常。 I am getting data in $name .我在$name获取数据。 But now i need to validate the input json.但现在我需要验证输入 json。 I need to set validation rule in ApiRequest for the name key like this我需要在ApiRequest为这样的name键设置验证规则

public function rules()
{
     return [
            'name' => 'required|min:6'
            ];
}

Help me to do this.帮我做这件事。 Thanks.谢谢。

Laravel validates AJAX requests the same way. Laravel 以同样的方式验证 AJAX 请求。 Just make sure you're setting one of these request headers on your request:只需确保您在请求中设置了以下请求标头之一:

'Accept': 'application/json'

'X-Requested-With': 'XMLHttpRequest'

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]));

        }

   }
}
    return $inputJson->toArray();   

and then pass to validator然后传递给验证器

    $name = ['name'=>'er'];
    $rules = array('name' => 'required|min:4');
    $validation = Validator::make($name,$rules);

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());    

}

Validating any headers can be done in clean way two steps:可以通过两个步骤以干净的方式验证任何标头:

Step 1: Prepare header data to request data in prepareForValidation method.第一步:在prepareForValidation方法中准备请求数据的头部数据。
public function prepareForValidation()
{
    $this->merge([
        "content_type" => $this->headers->get("Content-type"),
    ]);
}
Step 2: Apply any validation rules that you want, (Here, you want your data exact to be application/json . so第 2 步:应用您想要的任何验证规则,(在这里,您希望您的数据准确为application/json 。所以
public function rules(): array
{
    return [
        "content_type" => "required|in:application/json",
    ];
}

Complete Example looks like:完整示例如下所示:

/**
 * 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM