json - laravel验证Content-Type : application/json request

标签 json web-services laravel laravel-5

在laravel 5中,我提出了一个名为ApiRequest的新请求。

class ApiRequest extends Request
{
    public function authorize() {
      return $this->isJson();
    }
    public function rules()
    {
     return [
            //
            ];
    }
}

如您所见,我仅接受json数据。我正在像这样在 Controller 中接收json
public function postDoitApi(ApiRequest $payload) {
        $inputJson = json_decode($payload->getContent()); 
        $name = $inputJson->name;
}

哪个工作正常。我正在$name中获取数据。但是现在我需要验证输入的json。
我需要像这样为ApiRequest key 在name中设置验证规则
public function rules()
{
     return [
            'name' => 'required|min:6'
            ];
}

帮我做到这一点。谢谢。

最佳答案

您可以使用验证器方法代替规则方法:

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

        }

   }
}

关于json - laravel验证Content-Type : application/json request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31699400/

相关文章:

web-services - 如何将游戏化与 sharepoint 集成

c# - 数据契约WCF放在哪里?可以放入数据层吗?

php - 如何在 Laravel 中格式化输出 MySQL 日期?

php - Laravel - 使用 Query Builder 函数传递变量

javascript - 从 $.getJSON 迭代集合并将新对象推送到数组中会使数组为空

json - 将下面提到的 Json 字符串转换为字典

python - 将所有标签存储在艺术家[i] ['tags' ]

android - 具有字段更改的 REST Api JSON 响应

iphone - 在 Objective-C (iPhone) 中使用 SVC 网络服务

php - laravel Eloquent 一对一保存关系