Laravel Model Observer and How to Use It

Howdy laravel devs, in this example i will discuss about Laravel model observers. If you know don't know what is model observers and when to use it then this tutorial is for you.

Let assume you have a Posts model, you might want to send notifications of the new post to subscribers, or you might want to notify an admin every time a post is edited.

What is an Observer?

Observers are classes that contain methods that are triggered when a models state changes. Under the hood, Laravel triggers events that observers can listen to.

Observers can perform actions on createupdatedeleterestored and forceDelete.

When do Restored and forceDelete trigger?

These events are triggered on models that are using Soft Deletes, when either restoring or force deleting. Read more about soft deleting.

 

Creating an Observer

Well, here we go. There’s an artisan command to generate an Observer:

php artisan make:observer UserObserver --model=User

 

This will create the class in an Observers directory, and if you open up that new class you’ll see the following boilerplate:

namespace App\Observers;

use App\Models\User;

class UserObserver
{
    public function created(User $user)
    {
        //
    }

    public function updated(User $user)
    {
        //
    }

    public function deleted(User $user)
    {
        //
    }

    public function restored(User $user)
    {
        //
    }

    public function forceDeleted(User $user)
    {
        //
    }
}

 

As you can see, there’s a method for createupdatedeleterestored and forceDelete.

Here’s an example where we send a notification on update:

use App\Notifications\UserUpdated;

...

public function updated(User $user)
{
    $user->notify(new UserUpdated($user));
}

 

Registering Observers

To do this we add the following to the boot method of our App\Providers\EventServiceProvider service provider:

use App\Models\User;
use App\Observers\UserObserver;

...

public function boot()
{
    User::observe(UserObserver::class);
}

 

Skipping Observers

In that case, you can use the saveQuietly method instead, for example:

$user->saveQuietly();

 

Hope it can help you.