Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Check with Observer if Column was Changed on Update

I am using an Observer to watch if a user was updated.

Whenever a user is updated I would like to check if his email has been changed.

Is something like this possible?

class UserObserver
{


    /**
     * Listen to the User created event.
     *
     * @param  \App\User  $user
     * @return void
     */
    public function updating(User $user)
    {
      // if($user->hasChangedEmailInThisUpdate()) ?
    }

}
like image 328
Adam Avatar asked Feb 14 '18 17:02

Adam


3 Answers

Edit: Credits to https://stackoverflow.com/a/54307753/2311074 for getOriginal

As tadman already said in the comments, the method isDirty does the trick:

class UserObserver
{


    /**
     * Listen to the User updating event.
     *
     * @param  \App\User  $user
     * @return void
     */
    public function updating(User $user)
    {
      if($user->isDirty('email')){
        // email has changed
        $new_email = $user->email; 
        $old_email = $user->getOriginal('email');
      }
    }

}

If you want to know the difference between isDirty and wasChanged, see https://stackoverflow.com/a/49350664/2311074

like image 95
Adam Avatar answered Nov 01 '22 14:11

Adam


You don't have to get the user again from the database. The following should work:

public function updating(User $user)
{
  if($user->isDirty('email')){
    // email has changed
    $new_email = $user->email; 
    $old_email = $user->getOriginal('email'); 
  }
}
like image 18
user1415066 Avatar answered Nov 01 '22 16:11

user1415066


A little late to the party, but might be helpful for future devs seeking a similar solution.

I recommend using the package Laravel Attribute Observer, as an alternative to polluting your Service Providers or filling your Observers with isDirty() and wasChanged() boilerplate.

So your use case would look like this:

class UserObserver
{


    /**
     * Handle changes to the "email" field of User on "updating" events.
     *
     * @param  \App\User  $user
     * @param string $newValue The current value of the field
     * @param string $oldValue The previous value of the field
     * @return void
     */
    public function onEmailUpdating(User $user, string $newValue, string $oldValue)
    {
      // Your logic goes here...
    }

}

Laravel Attribute Observer is especially useful when you have a lot of attributes to observe on one or more models.

Disclaimer: I am the author of Laravel Attribute Observer. If it saves you some development time, consider buying me a coffee.

like image 2
alexstewartja Avatar answered Nov 01 '22 15:11

alexstewartja