Disabling Events in Laravel Model Observer

Robert Coster

Robert Coster

5 May 2021, 08:53

Disabling Events in Laravel Model Observer

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.


More Web Development & Laravel Posts

How to seed a geographical POINT using Laravel / MySQL

Guide: SSL Certificates

Guide: PHP Frameworks

Steps to Dokku and Postgres (with PostGIS) on Ubuntu 16.04

Guide: What is DNS?

Getting mcrypt extension working on PHP 7.3.6 and Homebrew on Macbook

Disabling Events in Laravel Model Observer

Guide: What is a domain name?