如何验证 json 对象中的请求 - 使用 laravel
Posted
技术标签:
【中文标题】如何验证 json 对象中的请求 - 使用 laravel【英文标题】:How to validate request in json objects - using laravel 【发布时间】:2019-08-31 16:01:08 【问题描述】:我的 json 有两个对象,一个是 user_profile,另一个是权限,但我的验证仅适用于 user_profile 对象。
我的 json:
"user_profile":
"email": "shahzad11@ovadamd.com",
"password": "admin123",
"password_confirmation": "admin123",
"status": 0,
"first_name": "Shahzad",
"middle_name": "Hussain",
"last_name": "Shah",
"date_of_birth": "2015-01-01",
"gender": "M",
"area_id": 1,
"address": "Minhatten NY",
"city": "New York",
"state": "Washington",
"zip": "12312",
"fax": "111-111-1111",
"phone_extension": "2471",
"work_phone": "111-111-1111",
"phone_no": "111-111-1111",
"emergency_contact": "111-111-1111",
"social_security": "111-11-1111",
"module_id": 2
,
"privileges":
"is_super_admin": 1,
"facilities": [
"facility_id": 1,
"is_facility_supervisor": 0,
"speciality_id": 1,
"priv_id": "",
"role_id": 1
]
我也想验证我的“特权”对象。
我的控制器:
public function register(Request $request)
$body = $request->all();
$userProfile = $body['user_profile'];
$userPrev = $body['privileges'];
$userProfile['is_super_admin'] = $userPrev['is_super_admin'];
$facilities = $userPrev['facilities'];
$bodyObj = array_merge($userProfile, $userPrev);
$validator = UserValidations::validateUser($bodyObj);
if ($validator->fails())
return response([
'status' => false,
'message' => __('messages.validation_errors'),
'errors' => $validator->errors()->all()
], 200);
还有我的 validateUser 方法:
public static function validateUser($data = [], $update = false)
$rules = [
'first_name' => 'required|max:25',
'last_name' => 'required|max:25',
"address" => 'required|max:197',
"city" => 'required|max:20',
"zip" => 'required|max:5',
"phone_no" => 'required|max:12',
"area_id" => 'exists:areas,id',
"phone_extension" => 'min:3|max:5',
'gender' => 'in:M,F,X',
"work_phone" => 'max:12',
"emergency_contact" => 'max:12',
"fax" => "max:12",
"social_security" => 'required|max:11',
"module_id" => 'exists:modules,id',
// privileges object fields
"role_id" => 'required|exists:roles,id',
"facility_id" => 'required',
"speciality_id" => 'required'
];
if($update)
$rules['id'] = 'required|exists:users,id';
else
$rules['email'] = 'required|email|unique:users';
$rules['password'] = 'required|min:6';
$rules['password_confirmation'] = 'required_with:password|min:6|same:password';
return $validator = Validator::make($data, $rules);
如何对特权对象进行验证? 非常感谢您的帮助!
【问题讨论】:
你不能在不同的验证器上验证它吗?我确实认为它会使其更易于维护和扩展。 【参考方案1】:// privileges object fields
"facilities.*.role_id" => 'required|exists:roles,id',
"facilities.*.facility_id" => 'required',
"facilities.*.speciality_id" => 'required'
我想它会解决你的问题
【讨论】:
【参考方案2】:你可以这样做
Validator::make($request->all(),[
'your rules'])
【讨论】:
我的对象不在 $request 中,我在验证器中使用了 $bodyobject 并合并了我的两个请求 为什么要这样做?请在您的答案中添加一些解释,以便其他人可以从中学习以上是关于如何验证 json 对象中的请求 - 使用 laravel的主要内容,如果未能解决你的问题,请参考以下文章