Home > database >  laravel model, adding attribute to model
laravel model, adding attribute to model

Time:04-28

I have a user model, and I want to add (an attribute to the user model) the user's email that it was before it was updated.

[email protected]
[email protected]

Within the user model, I have this function, I can get the before email, I was wondering I can assign some fake attribute, so I can access it like: $user->beforeEmail

protected static function booted()
{
    static::saved(function ($user) {
        $user->beforeEmail = $user->original['email'];
    });
}

$user->beforeEmail // [email protected]

The code above is not working but provided it to help illustrate what I am trying to accomplish.

CodePudding user response:

You could check if the email address has changed just before storing the new email to the db. This can be accomplished by using the saving event instead of the saved event.

protected static function booted()
{
   static::saving(function ($user) {
       if($user->isDirty('email')){
            $user->beforeEmail = $user->email
       }
   });
}

Note: Your code example will not save the changes automatically since the saved event is ran after executing the query. It's possible that your code works just by adding $user->save()

CodePudding user response:

Are you trying to get this value in the model or in a different class? As what you have works with a few adjustments already.

protected static function boot(){
    parent::boot();
    static::saved(function($user){
        $user->originalEmail = $user->original['email'];
    }
}

You can access originalEmail if you update the model in a controller or other class, like so:

$user = User::find(1);
$user->update([
          'email' => '[email protected]'
       ]);
// $user, $user->originalEmail, $user->some_test_accessor all return the correct values

I've also tested with an accessor, just to verify and it still works as though the value is available in the model. I'm not sure where you're attempting to access this value, though.

public function getSomeTestAccessorAttribute(){
    return $this->originalEmail;
}

Does any of this help?

  • Related