简体   繁体   中英

laravel validate Content-Type: application/json request

in laravel 5 i made a new request named 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

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

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

Help me to do this. Thanks.

Laravel validates AJAX requests the same way. 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.

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.
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
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",
        ];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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