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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42187533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:18:49  来源:igfitidea点击:

Check if request input is not null before set the value

phplaravelnulleloquentlumen

提问by dios231

I have an API that set user settings. Because neither of inputs are mandatory I want to check first if the value exists and then set it to the model attributes in order to avoid null values.

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

Specificaly when one of inputs is not existin I dont want to pass it to the model. Also I dont want to make inputs required

特别是当输入之一不存在时,我不想将其传递给模型。我也不想做需要的输入

回答by Achraf Khouadja

do this

做这个

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

Edit: Or use Form requests, it's a better approach

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

回答by B. Desai

Check each value and push it first into array. Then assign array.

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

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