Laravel

Laravel 10 Model Observers Tutorial Example

Share your learning

Today we are going to discuss Laravel model observers tutorial with examples.

Laravel is a powerful PHP framework that has revolutionized web development with its simplicity and robustness. One of the features that makes Laravel stand out is its support for Model Observers. 

Model Observers allow you to attach certain actions to specific events in your Eloquent models, making it easier to perform tasks like auditing, data manipulation, and notifications. 

In this tutorial, we will explore the concept of Model Observers in Laravel 10 and demonstrate their usage with a practical example.

Prerequisites

Before diving into this tutorial, you should have a basic understanding of Laravel and its Eloquent ORM. You should also have Laravel 10 installed on your system. If you haven’t done so, you can follow the official Laravel installation guide to set up your environment.

What are Model Observers?

Model Observers are classes that listen for specific Eloquent events and respond to them with custom logic. These events include creating, updating, deleting, and restoring (soft deleting) model instances

By defining an observer, you can decouple the logic related to these events from your models, leading to a cleaner and more maintainable codebase.

What are the Eloquent model events?

Below is a list of the Eloquent events that observers can listen to:

  1. retrieved: The event fires when the system retrieves a model from the database.
  2. creating: The system fires this event just before it saves a new model to the database.
  3. created: The system fires this event after successfully saving a new model to the database.
  4. updating: The system fires this event just before updating a model in the database.
  5. updated: The system fires this event after successfully updating a model in the database.
  6. saving: The system fires this event just before saving a model (creating or updating) in the database.
  7. saved: The system fires this event after successfully saving a model (creating or updating) in the database.
  8. deleting: The system fires this event just before deleting a model from the database.
  9. deleted: The system fires this event after successfully deleting a model from the database.
  10. restoring: The system fires this event just before restoring a soft-deleted model.
  11. restored: The system fires this event after successfully restoring a soft-deleted model.

Creating a Model Observer

To create a Model Observer in Laravel 10, follow these steps:

  1. Create the Observer Class: Start by generating a new observer class using the php artisan make:observer command. Replace ObserverName with a meaningful name for your observer.
php artisan make:observer ObserverName
  1. Defining Event Listeners: Open the newly created observer class in the app/Observers directory. Inside the class, you will find various methods corresponding to the Eloquent events you can listen to. For instance, the created method will be triggered when a new model instance is created.
namespace App\Observers;

use App\Models\YourModel;

class ObserverName
{
    public function created(YourModel $model)
    {
        // Your logic here
    }

    // Add more event listeners as needed
}

3. Registering the Observer: After defining your observer, you need to register it in the boot method of the AppServiceProvider (if it doesn’t already exist). This will ensure that Laravel knows about your observer and automatically triggers the event listeners when the corresponding events occur.

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Observers\ObserverName;
use App\Models\YourModel;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        YourModel::observe(ObserverName::class);
    }
}

Example: Auditing Article Edits

Let’s consider a practical example of using Model Observers to audit article edits in a blog application.

1. Create the Article Model: First, create an Eloquent model for the articles using the following command:

php artisan make:model Article -m

This command will generate the Article model along with a migration file to create the corresponding database table.

2. Add the necessary columns: In the migration file created for the articles table, add two additional columns: last_edited_by (to store the user ID of the last editor) and last_edited_at (to store the timestamp of the last edit). Run the migration to update the database.

3. Create the Observer: Now, create an observer called ArticleObserver using the command mentioned earlier.

php artisan make:observer ArticleObserver

4. Define Event Listeners: In the ArticleObserver class, define the updating event listener to capture article edits and update the last_edited_by and last_edited_at columns.

namespace App\Observers;

use App\Models\Article;
use Illuminate\Support\Facades\Auth;

class ArticleObserver
{
    public function updating(Article $article)
    {
        $article->last_edited_by = Auth::id();
        $article->last_edited_at = now();
    }
}

5. Register the Observer: Open the AppServiceProvider and register the ArticleObserver in the boot method.

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Observers\ArticleObserver;
use App\Models\Article;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Article::observe(ArticleObserver::class);
    }
}

With this setup, every time an article is updated, the updating method in the ArticleObserver will be triggered, automatically updating the last_edited_by and last_edited_at columns in the database.

Conclusion

In this tutorial, we have explored the concept of Laravel 10 Model Observers and demonstrated their implementation with a practical example. Model Observers help you decouple the logic related to Eloquent events from your models, resulting in cleaner and more maintainable code. By using them, you can easily perform tasks such as auditing, data manipulation, and notifications in response to specific model events.

Satpal

Recent Posts

How to Switch PHP Versions in XAMPP Easily: Managing Multiple PHP Versions on Ubuntu

Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…

1 year ago

How to Use Coding to Improve Your Website’s SEO Ranking?

Let's understand about how to use coding to improve your website's SEO. In today’s computerized…

1 year ago

Most Important Linux Commands for Web Developers

Let's understand the most important linux commands for web developers. Linux, as an open-source and…

1 year ago

Top 75+ Laravel Interview Questions Asked by Top MNCs

Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…

1 year ago

Mailtrap Integration for Email Testing with Laravel 10

Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…

1 year ago

Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications

Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…

1 year ago