Yahya Uddin
Yahya Uddin

Reputation: 28901

Avoid Eloquent model event from being triggered multiple/ infinite times using Laravel

I have the following code:

AppServiceProvider:

User::saved(function (User $user) {
    return $user->modifiedEvent();
});

User::deleted(function (User $user)   
    return $user->modifiedEvent();
});

In my User model I have:

    public function modifiedEvent()
    {
        $stage = $this->isDirty('terms_and_conditions') 
             && $this->terms_and_conditions !== null ? 'completed' : 'incomplete';
        $this->stage_terms_and_conditions = $stage;
        return $this->save();
    }

The issue I have is that the modifiedEvent also modifies the model, which means we get an infinite loop!

Whats the best way to make sure that this event is not triggered multiple times due caused by the event it self.

Upvotes: 1

Views: 592

Answers (1)

dparoli
dparoli

Reputation: 9171

I will try to use the 'saving' event so there is no need to call $this->save() at the end.

Upvotes: 2

Related Questions