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()) ?
}
}
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
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');
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With