laravel 5.2 - 检查字段是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37078366/
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
laravel 5.2 - check if field is empty or not
提问by user0111001101
I want to check if some field is empty or not. If is empty, the user can update the profile without change the current password. If is not empty, store new value of password. My controller is:
我想检查某个字段是否为空。如果为空,则用户可以在不更改当前密码的情况下更新配置文件。如果不为空,则存储密码的新值。我的控制器是:
public function storeUpdatedUser(Request $request)
{
$this->validate($request, ['email' => 'required', 'name' => 'required', 'surname' => 'required', ]);
$user = User::findOrFail(Auth::user()->id);
$user->update($request->all());
$new_password = false;
if($new_password != ""){
$new_password = bcrypt($request->new_password);
$user->password = $new_password;
}
$user->save();
Session::flash('flash_message', 'User updated!');
return redirect('/');
}
but dont work, no password change if I put some value
image explain better
回答by Felippe Duarte
Try this:
尝试这个:
public function storeUpdatedUser(Request $request)
{
$this->validate($request, ['email' => 'required', 'name' => 'required', 'surname' => 'required', ]);
$user = User::findOrFail(Auth::user()->id);
$user->update($request->all());
if(!empty($request->input('new_password'))) {
$new_password = bcrypt($request->input('new_password'));
$user->password = $new_password;
$user->save();
}
Session::flash('flash_message', 'User updated!');
return redirect('/');
}
回答by Hódos Gábor
This is what works for me in Laravel 5.7:
这在 Laravel 5.7 中对我有用:
$user = Auth::user();
$user->update($request->filled('password') ? $request->all() : $request->except(['password']));