Winter CMS resources and help articles

Simple and to the point. Optimized by the community.

Using Model::observe() to manage Model events

0
by mjauvin, last modified on May 25th, 2025

Laravel has a nice way of registering an Observer class to manage Model events:

You can monitor all Laravel events: retrieved, creating, created, updating, updated, saving, saved, restoring, restored, replicating, deleting, deleted, forceDeleting, forceDeleted

First, create an Observer class like this:

class MyModelObserver
{
    public function created($model) 
    {
        ...
    }
    public function updated($model) 
    {
        ...
    }
    public function deleted($model) 
    {
        ...
    }
}

Then, simply register the Observer class with your model(s) in the boot() method of your plugin:

public function boot()
{
    MyModel::observe(MyModelObserver::class);
}

An Observer class may be used by multiple models if needed:

public function boot()
{
    MyModel::observe(MyModelObserver::class);
    MyOtherModel::observe(MyModelObserver::class);
}

You can also add multiple Oberver classes to a model:

public function boot()
{
    MyModel::observe([Observer1::class, Observer2::class, ...]);
}

Discussion

0 comments

We use cookies to measure the performance of this website. Do you want to accept these cookies?