ihprince's avatar

How to Update data only if user changes anything?

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?

0 likes
4 replies
Snapey's avatar

why? What's the benefit to the user?

Snapey's avatar

That work's fine except image.

If the image is provided then it must be processed. If the image is not provided then don't replace it...

Snapey's avatar
Snapey
Best Answer
Level 122

You can do this instead. Let Eloquent do the work for you;

		$user->fill([
			'name'    => $request->name,
			'email'   => $request->email,
			'contact' => $request->contact,
			'image'   => $image,
        ]);

		if($user->isClean(){
			return back()->with('info', 'You have not change anything. Nothing to update!');
		}

        $user->save();

1 like

Please or to participate in this conversation.