首页 > 解决方案 > 仅当用户更改 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;
        }

我怎么能用图像做到这一点?最好的方法是什么?

标签: phpmysqllaraveleloquent

解决方案


由于 Eloquent 可以跟踪对模型所做的更改,因此我建议使用模型属性检查来确定模型是否::wasChanged().

由于您的原始脚本处理上传的文件并将$user->imageas 字符串保存到数据库,因此您需要将上传的文件源与当前图像文件源(如果有)进行比较,以确定是否应应用图像更改。

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()将忽略它遇到的任何非十六进制字符,并可能导致不希望的结果或数据丢失。

示例:https ://3v4l.org/aFGEJ

var_dump(hexdec("See"));
var_dump(hexdec("ee"));
// both print "int(238)"

推荐阅读