php - 仅当用户更改 laravel 中的任何内容时才更新数据
问题描述
仅当用户更改任何内容时才更新数据,否则会返回没有更新的消息。单击编辑按钮后,如果用户点击更新按钮而没有更改任何内容,则返回没有更新的消息。如果用户更改了编辑表单中的任何内容,那么它将被更新。
我试过这个
( I have multiple fields. This is for demo)
if ($user->name == $request->name && $user->email == $request->email && $user->contact ==
$request>contact) {
return back()->with('info', 'You have not change anything. Nothing to update!');
} else {
$user->update([
'name' => $request->name,
'email' => $request->email,
'contact' => $request->contact,
'image' => $image,
]);
}
return redirect()->route('admin.home')->with('success', 'Profile has been updated');
除了图像之外,这项工作很好。
这是我的图片上传过程
if ($request->has('image')) {
Storage::delete('public/avatar/users/' . $user->image);
$image_name = hexdec(uniqid());
$ext = strtolower($request->image->getClientOriginalExtension());
$image_full_name = $image_name . '.' . $ext;
$request->image->storeAs('avatar/users/', $image_full_name, 'public');
$image = $image_full_name;
} else {
$image = $user->image;
}
我怎么能用图像做到这一点?最好的方法是什么?
解决方案
由于 Eloquent 可以跟踪对模型所做的更改,因此我建议使用模型属性检查来确定模型是否::wasChanged()
.
由于您的原始脚本处理上传的文件并将$user->image
as 字符串保存到数据库,因此您需要将上传的文件源与当前图像文件源(如果有)进行比较,以确定是否应应用图像更改。
if ($request->has('image')) {
//only check image if supplied
if (!$user->image || sha1_file(Storage::path('public/avatar/users/' . $user->image)) !== sha1_file($request->image->path())) {
//apply image changes
if ($user->image) {
//remove previous image
Storage::delete('public/avatar/users/' . $user->image);
}
$image = str_replace('.', '', uniqid('', true)) . '.' . strtolower($request->image->getClientOriginalExtension());
$request->image->storeAs('avatar/users/', $image, 'public');
$user->fill(['image' => $image]);
}
}
$user->fill([
'name' => $request->name,
'email' => $request->email,
'contact' => $request->contact,
]);
$user->save();
if ($user->wasChanged(['name', 'email', 'contact', 'image'])) {
return redirect()->route('admin.home')->with('success', 'Profile has been updated');
}
return back()->with('info', 'You have not change anything. Nothing to update!');
免责声明
我不推荐使用hexdec(uniqid())
,赞成直接使用uniqid('', true)
。由于使用hexdec()
将忽略它遇到的任何非十六进制字符,并可能导致不希望的结果或数据丢失。
var_dump(hexdec("See"));
var_dump(hexdec("ee"));
// both print "int(238)"
推荐阅读
- django - Django模板变量(模型实例)翻译
- java - Intellij 无法解析符号 'lang3' apache
- mongodb - 启用用户访问控制后 MongoDB 身份验证失败
- c - 在 malloc 块中存储整数
- logging - How to print information in .net core test projects?
- javascript - Vue - Is there a way to scope $refs on a form
- ruby-on-rails - 启动服务器时的 Rails + ActiveStorage 问题 = 未定义的方法“has_one_attached”
- javascript - 以密码输入类型在手机上显示数字键盘
- java - 改进线性搜索技术?
- ms-access - 在插入前触发器中定义 SetField 值时如何指定字段 +1 的最大值?