Laravel Model Observers

Laravel: Model Observers

In the last tutorial I showed you how you can speed up a web application by caching database queries that are executed very often. However, there is a problem. Application will cache the resulted dataset, and in the future this dataset will be served. You need to tell your application to flush the cache every time when certain Model is updated. That way every time you edit, delete or add new Model item, old cache will be flushed, and query will be executed again. Afterwards, resulting new dataset will be cached and served until Model is updated once again.

Here Laravel Model Observers come in rescue. You can use them for numerous things. One of practical examples for using Model Observers is cache flushing.

Eloquent model

Let’s start with the model, here is basic Department model:

One of the places where you can put your observers is Eloquent boot method. We need to override the default boot method to add our observers:

Laravel Model Observers

Some of the code can be abstracted for later implementation, so we create AbstractionObserver class first:

Now we can implement this class to create any observer we need. For this purpose, let’s create one Department observer which will flush cache every time when Department model is updated.

Only thing left now is to cache some data. Here is a simple controller which handles IT Department resources, employees and everything else related to it:

By opening route departments/it we can see that one query is executed:

Laravel Model Observers - IT Department Cache Complex QueriesRefreshing the same page gives the same result, but no query is executed.

Laravel Model Observer - Cached Query for IT DepartmentOK. Now when we know that caching is working, how about making some changes in the Department model. What if we want to rename Development into, let’s say – DevOps.

I created DepartmentsApiController with basic CRUD operations, here you can see how update() method looks like, and what is result of PUT request:

Laravel Model Observers - Departments API ControllerLet’s refresh our departments/it route once again:

Query is executed once again and new dataset is cached for later use. This query will not be executed until new change in Department model triggers DepartmentObserver or until cache expires, which is for 1 hour.

I hope you now understand basic principle behind Model Observers and how this powerful feature can be used for other things that require notification on Model update.


Follow me

Mirza Pasic

Full Stack Developer at OLX
Web Developer. Geek. Systematic. Dreamer
Follow me

Published by

Mirza Pasic

Web Developer. Geek. Systematic. Dreamer

  • Umair Ahmed

    Can we make a general observer for all models, attached to a BaseModel?

    • Yes, why not? But it also depends on what you want to do on a Model you observe.

  • linkawes weska

    Hey, what tool is that you use to view database queries and results on the png attached?