PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, March 2, 2022

[FIXED] Laravel: Check with Observer if Column was Changed on Update

 March 02, 2022     laravel-5, mysql, php     No comments   

Issue

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()) ?
    }

}

Solution

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



Answered By - Adam
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing