Reputation: 13
I have created an Event and Listener. When a user's profile is updated it's gonna trigger and send the email.
boot
method in User
model:
public static function boot()
{
parent::boot();
static::updated(function ($user) {
if ($user->user_status == 'Active') {
event(new UserStatusChangeEvent($user));
}
});
}
The UserStatusChangeEvent
event class looks like this:
class UserStatusChangeEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user;
public function __construct($user)
{
$this->user = $user;
}
}
I am adding the listener in EventServiceProvider
's $listen
variable:
UserStatusChangeEvent::class => [
UserStatusChangeListener::class,
],
And in the listener
, I am sending mail by using the Mail Facade.
Now the thing is this is sending emails to all users whose status is Active
and updated
their profiles. But I want this to trigger when user_status
becomes Active
not on anything else.
Like there are 2 fields in users table user_status and is_active when the user logged in the is_active will become 1 and when the user logged out the status becomes 0 now if the user logged in or out, the event in boot method will trigger if the status is active but I want this to trigger when only status column changes should not trigger if is_active changes
Upvotes: 0
Views: 1369
Reputation: 8082
As you explained, you only want this to trigger when the column user_status
changes. But when the user logs in or out, you change is_active
, and because the user already has user_status = "Active"
it will trigger every time you do any change to the user (except changing user_status
).
So, to see if user_status
was updated, you can take advantage of the dirty
status.
static::updated(function ($user) {
if ($user->wasChanged('user_status') && $user->user_status === 'Active') {
event(new UserStatusChangeEvent($user));
}
});
See that I used wasChanged
.
Upvotes: 1