laravel 在设置值之前检查请求输入是否不为空

7gcisfzg  于 2023-06-25  发布在  其他
关注(0)|答案(4)|浏览(118)

我有一个设置用户设置的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);

特别是当一个输入不存在时,我不想把它传递给模型。此外,我不想使输入所需的

rks48beu

rks48beu1#

这个问题的答案取自here

if($request->filled('user_id'))
pdsfdshx

pdsfdshx2#

这样做

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

编辑:或者使用表单请求,这是一个更好的方法

kupeojn6

kupeojn63#

检查每个值并将其首先推入数组。然后分配数组。

<?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);
?>
w9apscun

w9apscun4#

$request->validate([
  'name'=>['required'],
])

然后呢

if(!is_null($request->name)){}

相关问题