How can I detect a change to a specific element in the auth()->user() object?
The general scenario is:
- user is logged-in and the auth()->user() contains a copy of the User model
- A field in the User database table is updated by another (CMS) application
- When the auth()->user() object is next updated, I need to compare the previous value of the field to the current value that was retrieved from the database
I think the easiest solution is to assign the field's value to a session variable BEFORE the auth()->user() is updated, but I cannot figure out where to insert such a session var assignment.
CodePudding user response:
If your problem is update the user model with the data modified, you can rehidrate the model instance by using
auth()->user()->fresh();
additionally you can eager loads any relation in the model.
auth()->user()->fresh('comments');
In the case you need to compare if any property in the instance have changed making a copy of the original before calling fresh method, you will have to compare properties, unless exists a method which could compare both instances directly, which I don´t know
CodePudding user response:
It looks like adding an event listener to my User model will do the trick:
/**
* MODEL EVENTS:
*/
public static function boot() {
parent::boot();
// extra actions when retrieving
static::retrieved(function($model) {
if (Session::get('member_type') != $model->member_type) {
Session::put('previous_member_type', Session::get('member_type'));
Session::put('member_type', $model->member_type);
}
});
}
Each time the User model is retrieved, I update 2 session variables, one containing the current value, the other containing the previous value.