REST API请求参数验证Laravel

时间:2017-04-27 05:52:05

标签: php laravel-5

我是Laravel的API新手。我正在尝试通过Laravel的验证方法验证发送到POST请求的参数。

以下数据是我通过POST请求发送的唯一参数。我想使用Laravel的验证方法验证device_id的唯一性。

data => {"device_id":"xxxxxx2C-9EA3-4FFB-B26D-E8E483xxxxxx","password":"ANVp285x","user_type":"1"} 

我可以验证唯一的数据参数,但是没有正确的响应或错误消息它会抛出异常。我的主要动机是验证device_idpassworduser_type

这是我的控制器商店

public function store(Request $request) {

    try {
        $result = $this->validate($request, [
            'data' => 'required',
//                'data.device_id' => 'required|unique:users|max:60',
//                'data.password' => 'required|min:6|confirmed',
//                'data.user_type' => 'required',
        ]);
        $user = new User;
//        Parameters from request
        $data = json_decode($request->data, TRUE);
        $user->device_id = $data['device_id'];
        $user->password = bcrypt($data['password']);
        $user->u_type = $data['user_type'];

//        Parameters to be generated
        $user->qr_code_image = "test_qr_code.png";
        $user->access_code = MyHelper::generate_access_code();
        $user->save();
        $user = User::find($user->id);
        $result = Fractal::item($user, new UserTransformer)->getArray();
        if (!empty($result['data'])) {
            $result['status'] = TRUE;
            $result['message'] = 'Success';
        } else {
            $result['status'] = FALSE;
            $result['message'] = 'Failed';
        }
    } catch (\Exception $e) {
        $result['status'] = FALSE;
        $result['message'] = 'Failed';
    }
    return $result;
}

2 个答案:

答案 0 :(得分:6)

您可以使用Illuminate\Support\Facades\Validator来验证API中的请求:

 $validator = Validator::make($request->all(), [
        "device_id" => "required|unique:devices",
        "user_type" => "required",
        "password"  => "required",
    ]);

    if ($validator->fails()) {
        return response(
            $validator->errors(),
            400
        );
    }

答案 1 :(得分:0)

我在approch下面找到了解决方法,

$data = $request->data;
        $data = json_decode($data, TRUE);
        $status = 200;
        $validator = Validator::make(
                        array(
                    "goal_title" => $data['goal_name'],
                    "family_id" => $data['family_id'],
                    "goal_frequency" => $data['goal_frequency'],
                        ), array(
                    "goal_title" => "required|regex:/(^[A-Za-z0-9 ]+$)+/|:family_goals",
                    "family_id" => "required",
                    "goal_frequency" => "required:goal_frequencies",
                        )
        );