简体   繁体   中英

How to know if model has changed after submit a form in Laravel 5.5?

I have a view with a form where the user can change his name. After submit the form, I need to know if the name has changed or not. At this momment, the code result allways in false (no changes), but the database table is updated correctly.

My User model has:

   protected static function hasChanged()
{
    self::updating(function($user){
      if($user->isDirty())
      {
            return true;
      }else
      {
          return false;
      }

    });
}

My ProfileController received the data in form.

    public function updateProfile(Request $request)
{
    $usuario = new User;
    User::find(Auth::user()->id)->update($request->all());
    $message = User::hasChanged() ? "Data changed" : "No data changed";
    return redirect('home')->with('success', $message); 
}

In $message allways get "No data changed", in spite of user has changed the data in the form.

I don't know if this is the best way to do it.

Thanks for help me.

The way that you have the hasChanged() method set up, this is actually not doing what you want it to do. Currently in your code, the hasChanged() method is registering an event handler for when the object is updating every time it is called. That means that hasChanged() doesn't actually return anything at all but it is adding a lot of unneeded overhead to your code in the long run.

What you'll want to do is split your call up into a couple of parts. When you call:

->update($request->all());

That is putting the values from the request into the object and then saving it all in one go. What you want to do is put the values into the object, then check to see if anything changed and then save it to the DB.

That will look something more like this:

$user = User::find(Auth::user()->id);
$user->fill($request->all());
$message = $user->isDirty() ? "Data changed" : "No data changed";
$user->save();
return redirect('home')->with('success', $message); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM