我有一个设置用户设置的API。由于这两个输入都不是必需的,我想首先检查该值是否存在,然后将其设置为模型属性以避免空值。
$this->InputValidator->validate($request, [
'firsname' => 'string',
'lastname' => 'string',
'email' => 'email',
'mobile_phone' => 'string',
'address' => 'string',
'language' => 'string',
'timezone' => 'string',
'nationality' => 'string',
'profile_photo' => 'url'
]);
$userInformation = new UserInformation([
'firstname' => $request->input('firstname'),
'lastname' => $request->input('lastname'),
'email' => $request->input('email'),
'mobile_phone' => $request->input('mobile_phone'),
'address' => $request->input('address'),
'profile_photo' => $request->input('profile_photo')
]);
$User->information()->save($userInformation);
具体来说,当其中一个输入不存在时,我不想将其传递给模型。我也不想输入
这个
问题的答案来自这里:
if($request->filled('user_id'))
这样做
$userInformation = new UserInformation;
if(request->has('firstname')){
$userInformation->firstname = $request->firstname;
}
if(request->has('lastnme')){
$userInformation->lastname = $request->lastname;
}
// do it for all
$User->information()->save($userInformation);
编辑:或使用表单请求,这是一种更好的方法
检查每个值并首先将其推送到数组中。然后分配数组。
<?php
$userArray=array();
if($request->input('firstname') != "") $userArray['firstname']=$request->input('firstname');
if($request->input('lastname') != "") $userArray['lastname']=$request->input('lastname');
if($request->input('email') != "") $userArray['email']=$request->input('email');
if($request->input('mobile_phone') != "") $userArray['mobile_phone']=$request->input('mobile_phone');
if($request->input('address') != "") $userArray['address']=$request->input('address');
if($request->input('profile_photo') != "") $userArray['profile_photo']=$request->input('profile_photo');
$userInformation = new UserInformation($userArray);
?>
$request->validate([
'name'=>['required'],
])
和
if(!is_null($request->name)){}