Update data only if user change anything in laravel

87
February 14, 2021, at 7:20 PM

Update data only if the user changes anything otherwise return a message that nothing to update. After click the edit button, if the user hits update button without change anything then return message nothing to update. If the user changes anything in the edit form then it will be updated.

I tried with this

( 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');

That work's fine except image.

Here is my image upload process

 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;
        }

How can I do this with image? What is the best way to do that?

Answer 1

You can check with a boolean value :

$update = $user->update([
        'name' => $request->name,
        // other fields
        'image'   => $image,
    ]);
if($update) {
    return redirect()->route('admin.home')->with('success', 'Profile has been updated');
} else {
    return back()->with('info', 'You have not change anything. Nothing to update!');
}

Here $update will return true if any field has changed, otherwise it will return false

Answer 2

Since Eloquent can track changes made to the model, I recommend using Model Attribute Examinations to then determine if the model ::wasChanged().

As your original script processes an uploaded file and persisted the $user->image as string to the database, you need to compare the uploaded file source with the current image file source (if any), to determine if the image changes should be applied.

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!');

Disclaimer

I do not recommend using hexdec(uniqid()), in favor of directly using uniqid('', true). As the usage of hexdec() will ignore any non-hexadecimal characters it encounters and may cause undesired results or loss of data.

Example: https://3v4l.org/aFGEJ

var_dump(hexdec("See"));
var_dump(hexdec("ee"));
// both print "int(238)"
Answer 3
$updatedUser = $user->update([
    'name' => $request->name,
    'email' => $request->email,
    'contact' => $request->contact,
    'image' => $image,
]);
if (serialize($user) == serialize($updatedUser)) {
   // user has updated something
} else {
  // no changes were made
}
READ ALSO
How to make webpack ignore a require to a mising file in a npm module?

How to make webpack ignore a require to a mising file in a npm module?

When bundling my project with webpack, I encountered an error message indicating that anode file required in one of my npm package does not exist

61
Dynamically loading property value from active list of profiles and set the value in configuration XML file

Dynamically loading property value from active list of profiles and set the value in configuration XML file

I have a spring bath application which contains a batch configurationI want to dynamically load profile based upon the environemnt variable parameter of active profile list

75
WorkManager using setForegroundAsync() with ListenableWorker

WorkManager using setForegroundAsync() with ListenableWorker

A very useful guide and code snippet is provided for using setForegroundAsync() for a long-running worker in the context of a Worker in WorkManager

78