DEV Community

Cover image for Laravel Observers: The Silent Ninjas of Your Application Lifecycle
Dharmik Bhadkoliya
Dharmik Bhadkoliya

Posted on

Laravel Observers: The Silent Ninjas of Your Application Lifecycle

Introduction

Imagine that whenever you submit a form on a website, An invisible assistant comes in and checks everything again. Add additional details Or even send a welcome letter without you having to lift a finger. Laravel observers are like behind-the-scenes assistants who work quietly. And it's powerful to handle all the tasks when you need them. In this post, we'll dive into how observers work in Laravel, why they're your app's silent ninjas in model event handling. and how to get the most out of those events in real-world examples.

What are Laravel Observers?

Laravel Observers are listener classes that help manage the lifecycle of your model by observing specific events, such as creating, updating, or deleting. Observers can define actions for each of these events. Keep your controllers and models clean and focused. The Observers act as "event experts" within your application Observers will handle the backend work required to improve your codebase. and improve organization and efficiency With event-driven work separation. Observers contribute to a more modular and maintainable application structure.

Why Use Observers?

1. Cleaner Controllers and Models: Observers handle repeated actions, letting your controllers and models focus on their main jobs without distraction.

2. Code Reusability: You can consolidate related actions in one place, making your code more readable and maintainable.

3. Error Handling: Observers help you avoid errors by automating tasks like data validation or background updates whenever a model changes.

4. Automatic Event Handling: Want to trigger an action every time a record is created or updated? Observers have your back.

In short, Observers are fantastic for organizing logic that you want to execute during the various stages of your app’s lifecycle.

Eloquent Hooks Overview:

- Retrieved: Triggered after a record is retrieved from the database.
- Creating: Fires just before a new record is created.
- Created: Executes after a new record is created successfully.
- Updating: Activates before an existing record is updated.
- Updated: Fires after a record has been updated.
- Saving: Runs before a record is saved, whether it's a new creation or an update.
- Saved: Occurs after a record has been saved, whether newly created or updated.
- Deleting: Initiates before a record is deleted or soft-deleted.
- Deleted: Activates after a record is deleted or soft-deleted.
- Restoring: Fires before a soft-deleted record is restored.
- Restored: Runs after a soft-deleted record has been successfully restored.

Step-by-Step Guide: How to Create and Use Observers

Let's discuss Observers with a real-world example. Imagine we’re building a blogging app, and every time a user publishes a post, we want to:

  • Automatically generate a slug from the title.
  • Notify an admin.
  • Record the publish date.

Here’s how we can make this happen with Laravel Observers!

Step 1: Create the Observer Class
Laravel makes it easy to generate an observer class. Run this command:

php artisan make:observer PostObserver --model=Post
Enter fullscreen mode Exit fullscreen mode

This will generate a PostObserver class in the app/Observers directory and link it to our Post model.

Step 2: Define the Events in the Observer

Open up the PostObserver class, and you’ll see some handy methods already in place. Each method corresponds to a model event, like creating, updating, deleting, and more.

Let’s add our custom logic to the creating event so that it generates a slug and records the publish date:

use Illuminate\Support\Str;
class PostObserver
{
   public function creating(Post $post)
   {
       $post->slug = Str::slug($post->title);
       $post->published_at = now();
   }

   public function created(Post $post)
   {
      Notification::send(User::admin(), new PostPublishedNotification($post));
   }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Register the Observer

Laravel offers two ways to do this: the ObservedBy attribute on the model or manually using the observe method

1.Using the ObservedBy Attribute

If you’re working with Laravel 10+, you can use the ObservedBy attribute directly on your model. This attribute simplifies Observer registration by automatically linking the Observer to the model:

use App\Observers\PostObserver;
use Illuminate\Database\Eloquent\Concerns\ObservedBy;

#[ObservedBy(PostObserver::class)]
class Post extends Model
{
   // Your Post model code
}
Enter fullscreen mode Exit fullscreen mode

This approach is clean and keeps the Observer registration with the model itself, reducing setup steps and keeping your AppServiceProvider untouched.

2.Manually Registering the Observer
If you prefer (or are working in a Laravel version prior to 10), you can manually register the Observer in the AppServiceProvider’s boot method:

In your App\Providers\AppServiceProvider.php, add the observe method to link the Observer to the model:

use App\Models\Post;
use App\Observers\PostObserver;

public function boot()
{
   Post::observe(PostObserver::class);
}
Enter fullscreen mode Exit fullscreen mode

Once registered, Laravel will trigger your Observer’s methods whenever the corresponding events occur on the Post model.

Step 4: Testing Your Observer

To see your observer in action, try creating or updating a post in your app. The slug will generate automatically, the publish date will set itself, and our hypothetical admin will receive a notification. Observers make all this happen quietly, just like a true ninja.


Thanks for reading! I hope this sparked some fresh ideas for your projects. If you're interested in bringing quality development to life, feel free to reach out—I’d love to connect and explore how we can make it happen.

Top comments (0)