Laravel 仅在不为空时更新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43632109/
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 only update if not null
提问by kjdion84
Is there a way of condensing the following code into a single update()?:
有没有办法将以下代码压缩成一个update()?:
$this->validate(request(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users,email,'.$id,
'password' => 'nullable|string|min:6|confirmed',
'timezone' => 'required|timezone',
]);
$user = User::findOrFail($id);
$user->update(request()->all());
if (!empty(request()->input('password'))) {
$user->update(['password' => bcrypt(request()->input('password'))]);
}
I want to get rid of the conditional statement for updating the password because I am using a mutator to bcryptit automatically now. Is there a method like request()->allNotNull()?
我想摆脱更新密码的条件语句,因为我现在正在bcrypt自动使用修改器。有类似的方法request()->allNotNull()吗?
回答by Alexey Mezenin
You can do this:
你可以这样做:
$user = User::where('id', $id)->update(request()->all());
Maybe you'll also want to add ->take(1).
也许您还想添加->take(1).
Update
更新
In comments you've said you want to get rid of empty fields. Use array_filter():
在评论中,您曾说过要摆脱空字段。使用array_filter():
array_filter($request->all());
If no callback is supplied, all entries of array equal to
falsewill be removed.
如果未提供回调,
false则将删除等于数组的所有条目。
回答by oseintow
You can try this. Password will be filtered out if password is empty.
你可以试试这个。如果密码为空,密码将被过滤掉。
$input = collect(request()->all())->filter()->all();
$user = User::where('id', $id)->update($input);

