Introduction

When working with Laravel Eloquent, you often need to execute certain actions whenever a model is created, updated, or deleted. Instead of cluttering controllers and models with event-handling logic, Laravel provides Observers to handle model events efficiently.

In this guide, we’ll cover everything about the Observer pattern in Laravel 10, including a Laravel Observer example, how to use updateOrCreate(), and when to use Observers for better application maintainability.


What is an Observer in Laravel 10?

An Observer in Laravel 10 is a class that listens for changes in a model and executes predefined logic when an event occurs. This follows the Observer Pattern, allowing developers to centralize event-handling logic instead of scattering it across models or controllers.

Why Use Laravel Observers?

  • Keeps code clean by moving event logic out of models
  • Improves maintainability by centralizing logic
  • Enhances reusability across different models
  • Helps with logging, caching, and notifications automatically

Laravel Observer Events

Laravel provides several model events that Observers can listen to:

EventDescription
retrievedTriggered when a model is fetched from the database
creatingBefore a model instance is created
createdAfter a model instance is created
updatingBefore updating a model instance
updatedAfter updating a model instance
savingBefore a model is saved (create or update)
savedAfter a model is saved (create or update)
deletingBefore deleting a model instance
deletedAfter deleting a model instance
restoringBefore restoring a soft-deleted model
restoredAfter restoring a soft-deleted model

These events make it easy to hook into model changes and trigger actions.


Laravel Observer Example

Let’s create an Observer for the User model that logs messages whenever a user is created, updated, or deleted.

Step 1: Generate an Observer

Run the following command to create an Observer:

php artisan make:observer UserObserver --model=User

Step 2: Define Observer Methods

Modify UserObserver.php to define logic for the events you want to listen to.

namespace App\Observers;

use App\Models\User;
use Illuminate\Support\Facades\Log;

class UserObserver
{
    /**
     * Handle the User "creating" event.
     */
    public function creating(User $user)
    {
        Log::info('A new user is being created: ' . $user->email);
    }

    /**
     * Handle the User "updated" event.
     */
    public function updated(User $user)
    {
        Log::info('User updated: ' . $user->email);
    }

    /**
     * Handle the User "deleted" event.
     */
    public function deleted(User $user)
    {
        Log::info('User deleted: ' . $user->email);
    }
}

creating(): Runs before a user record is inserted into the database.

updated(): Runs after the user model is updated.

deleted(): Runs after the user is deleted.

Registering the Laravel Observer

After defining the Observer, you must register it inside AppServiceProvider.php.

Open app/Providers/AppServiceProvider.php and modify the boot() method:

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

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

Now, Laravel will automatically trigger the Observer’s methods whenever a User model event occurs.


Laravel updateOrCreate in Observer

Sometimes, instead of creating or updating a record separately, you may want to use Laravel’s updateOrCreate() method inside an Observer.

Example: Using updateOrCreate() in an Observer

Let’s say we have a Profile model associated with a User and we want to update or create a profile whenever a user updates their information.

Modify the UserObserver.php file:

use App\Models\Profile;

public function updated(User $user)
{
    Profile::updateOrCreate(
        ['user_id' => $user->id], 
        ['email' => $user->email, 'name' => $user->name]
    );
}

Here’s how it works:

  • If a profile for the user exists, it updates it.
  • If no profile exists, it creates one.

This is a perfect use case for Laravel updateOrCreate, ensuring efficient data handling in Observers.


Real-World Use Cases for Laravel Observers

1. Logging Model Changes

Laravel Observers are great for keeping track of changes.

public function updated(User $user)
{
    Log::info("User {$user->id} updated their profile.");
}

2. Sending Notifications

Observers can automatically notify users when an event occurs.

use App\Notifications\WelcomeEmail;
use Illuminate\Support\Facades\Notification;

public function created(User $user)
{
    Notification::send($user, new WelcomeEmail());
}

3. Auto-Updating Related Data

If a user’s email changes, we might need to update a related Orders table.

public function updated(User $user)
{
    $user->orders()->update(['email' => $user->email]);
}

4. Caching Optimization

If a model update affects frequently accessed data, clear the cache.

public function updated(User $user)
{
    Cache::forget('user_'.$user->id);
}

When Not to Use Observers

While Observers are useful, they may not be the best approach in every case:

For Simple Model Events: If the logic is just a few lines, consider placing it inside the model instead.
If Performance is Critical: Observers can slow down database operations. Use Laravel Jobs & Queues instead.
For Decoupled Architecture: If your application uses microservices, Laravel Events & Listeners might be a better choice.


Conclusion

The Observer pattern in Laravel 10 is a powerful way to handle Laravel model events cleanly. Whether you’re logging events, sending notifications, auto-updating related data, or using updateOrCreate, Observers make event handling structured and maintainable.

By using Laravel Observers, you enhance your code’s scalability, organization, and efficiency—ensuring that your application is well-structured as it grows.

Now it’s your turn! Try implementing a Laravel Observer example in your project and optimize your event-driven logic effortlessly.


FAQs

1. What is the purpose of Observers in Laravel 10?

Observers in Laravel listen to model events and help execute logic when data is created, updated, or deleted.

2. How do you create an Observer in Laravel?

Use this command:

php artisan make:observer UserObserver --model=User

Then, register it in AppServiceProvider.php.

3. What is Laravel updateOrCreate?

The updateOrCreate() method updates an existing record or creates a new one if no match is found.

4. How are Observers different from Events in Laravel?

  • Observers are tied to model changes.
  • Events & Listeners offer more flexibility and work across the application.

Categorized in: