Disabling Events in Laravel Model Observer

Robert Coster
1 min readAug 31, 2019

I needed to create a model observer for a recent project to add a value to a model after being edited in Laravel Nova. The ideal event for this was creating but unfortunately due to limitations in a package I was using (MySQL Spatial / API stuff) I couldn’t use this. So I needed to use created. I also needed to run the event on the model being updated. Uh oh, yep, run-away events. The created event caused the update event to run, which then caused the update event to run, which then caused the update event to run etc… Not good…

The answer I found was to use the following statement prior to the $model->save() event in the created event…

$model::unsetEventDispatcher();

This has the effect of temporarily disabling further events caused when the created event is fired, preventing the updated event from firing which is what I wanted. I believe there are other ways to do this (Google / Stack Overflow are your friends) but this was the best way I found to do this that worked quickly.

Article also available along with others on my website https://signalfire.co.uk/blog

--

--

Robert Coster

Web Developer using #php, #node and other open source web platforms. i like to say stuff on politics as well.