编程语言
首页 > 编程语言> > php-在设置值之前检查请求输入是否不为null

php-在设置值之前检查请求输入是否不为null

作者:互联网

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

具体来说,当输入之一不存在时,我不想将其传递给模型.我也不想输入

解决方法:

做这个

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

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

标签:lumen,laravel,eloquent,null,php
来源: https://codeday.me/bug/20191118/2024527.html