laravel observers

What are Laravel model observers ?

Hello Guys,

Today am going to be writting about laravel observers.

Laravel ships with alot of amazing features, I recently came to learn about laravel model observers when i was faced with a simple challenge.

To help you understand i will be explaining what observers are in Laravel with an example.

Let’s begin by learning the observer pattern

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. Source : Wikipedia

In Laravel the observer pattern can be seen in Eloquent which provides a convenient way to add your own action while the model is completing or has completed some action.

Let’s look at an example that made me use Laravel observers

I wanted to create an activity log functionality where when a user creates , reads ,updates or deletes (basically CRUD) anything in a particular model it should log that activity into the database.

I looked around various ways example using a package by spatie or creating my own methods to do this and then adding them on the controllers / actions where i have written these CRUD functionalities.Both ways seemed to be tedious since it will require me to go over a heavy project with alot of lines of code then add a line of code to the CRUD methods.

Then i thought … what if i can tap into to the save event from a model then just after that action i can log the event,This seemed not only to save me time but a small amount of work to do and luckly it’s possible in laravel.

For example, if you have Product model and you want to log it automatically when a product is saved/created. You can listen to the saved event and log it:

How It Works

You first create a model observer for the particular model in question like below

php artisan make:observer ProductObserver — model=Product

Above command will create a new class located in the app/Observers folder. Your newly created observer class will look like below:

namespace App\Observers;

use App\Models\Product;

class ProductObserver
{
/**
* Handle the product "created" event.
*
* @param \App\
Models\Product $product
* @return void
*/

public function created(Product $product)
{
//
}

/**
* Handle the product "updated" event.
*
* @param \App\
Models\Product $product
* @return void
*/

public function updated(Product $product)
{
//
}

/**
* Handle the product "deleted" event.
*
* @param \App\
Models\Product $product
* @return void
*/

public function deleted(Product $product)
{
//
}

/**
* Handle the product "restored" event.
*
* @param \App\
Models\Product $product
* @return void
*/

public function restored(Product $product)
{
//
}

/**
* Handle the product "force deleted" event.
*
* @param \App\
Models\Product $product
* @return void
*/

public function forceDeleted(Product $product)
{
//
}
}

Now you have to register this class in Laravel’s Service Container, so we will add this class in AppServiceProvider‘s boot() method by telling Product model to observe the ProductObserver class, like below:

namespace App\Providers;

use App\Models\Product;
use App\Observers\ProductObserver;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/

public function register()
{
//
}

/**
* Bootstrap any application services.
*
* @return void
*/

public function boot()
{
Product::observe(ProductObserver::class);
}
}

In our ProductObserver class, Laravel created some function by default like created, updated and others. We will delete all of them and add a saved hook by telling to log an activity after a product is saved.

Replace your observer class with below.

namespace App\Observers;

use App\Models\Product;
class ProductObserver
{
/**
* Handle the product "saved" event.
*
* @param \App\Models\$Product $product
* @return void
*/

public function saved(Product $product)
{
log_activity()...
}
}

Now we have successfully added a model observer to observe our Product model, whenever you create a new product, it will log that activity.

remember you can do this to other CRUD acitivities as well using the following hooks
Retrieved
Creating
Created
Updating
Updated
Saving
Saved
Deleting
Deleted
Restoring
Restored

Test the above and let me know how it goes on the comment section

Before you go… Thanks for reading the article! If you enjoyed it, please don’t forget to show your appreciation by clicking 👏 below!

Any questions or comments hit me up on

Mail: epmnzava@gmail.com

Twitter: https://twitter.com/epmnzava

Github: https://github.com/dbrax

Software Engineer and techprenuer with passion of helping entreprenuers and small businesses using Technology