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

时间:2017-02-12 12:30:40

标签: php laravel null eloquent lumen

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

具体来说,当其中一个输入不存在时,我不想将其传递给模型。此外,我不想要输入

3 个答案:

答案 0 :(得分:2)

这样做

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

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

答案 1 :(得分:0)

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

$ python
Python 3.5.2 |Continuum Analytics, Inc.| (default, Jul  2 2016, 17:52:12)
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> v = example.generate_vector(64)
>>> print(v)
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

答案 2 :(得分:0)

此问题的答案摘自here

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