Chapter 8 - Laravel Observers

Hello Artisan's, welcome to the 8th chapter of being an Artisanary. In tis chapter we'll discuss about Observers. So if you already complete the previous chapters/sections, then you're good to go, if not my recommendation would be please complete the previous chapters. Because we'll use the same old repository that we use in chapter 4. 

Note: Tested on Laravel 10.0

Table of Contents

  1. Create and Setup Observer
  2. Different Methods of Observer
  3. Conclusion

Create and Setup Observer

To create a observer, fire the below command in your terminal

php artisan make:observer BlogObserver --model=Blog

It'll create a file called BlogObserver.php under app/Observers. The file will look like below 

app/Observers/BlogObserver.php
<?php

namespace App\Observers;

use App\Models\Blog;

class BlogObserver
{
    /**
     * Handle the Blog "created" event.
     */
    public function created(Blog $blog): void
    {
        //
    }

    /**
     * Handle the Blog "updated" event.
     */
    public function updated(Blog $blog): void
    {
        //
    }

    /**
     * Handle the Blog "deleted" event.
     */
    public function deleted(Blog $blog): void
    {
        //
    }

    /**
     * Handle the Blog "restored" event.
     */
    public function restored(Blog $blog): void
    {
        //
    }

    /**
     * Handle the Blog "force deleted" event.
     */
    public function forceDeleted(Blog $blog): void
    {
        //
    }
}

Now we've to register the Observer in EventServiceProvider boot() as below

app/Providers/EventServiceProvider.php
<?php

namespace App\Providers;

use App\Models\Blog;
use App\Observers\BlogObserver;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
    ];

    public function boot(): void
    {
        Blog::observe(BlogObserver::class);
    }

    public function shouldDiscoverEvents(): bool
    {
        return false;
    }
}

Different Methods of Observer

Laravel Observers provide some useful methods that can be used to listen for specific events on an Eloquent model. The available methods are:

  • Retrieved: After a record has been retrieved.
  • Creating: Before a record has been created.
  • Created: After a record has been created.
  • Updating: Before a record is updated.
  • Updated: After a record has been updated.
  • Saving: Before a record is saved (either created or updated).
  • Saved: After a record has been saved (either created or updated).
  • Deleting: Before a record is deleted or soft-deleted.
  • Deleted: After a record has been deleted or soft-deleted.
  • Restoring: Before a soft-deleted record is going to be restored.
  • Restored: After a soft-deleted record has been restored

We'll see the usage of creating() and created() method as of our example. So, put the below code in yours observer.

public function creating(Blog $blog)
{
  $blog->slug = Str::slug($blog->title);
}
public function created(Blog $blog): void
{
  $blog->unique_id = 'PR-'.$blog->id;
  $blog->save();
}

So, the BlogObserver.php file will look like these.

app/Observers/BlogObserver.php
<?php

namespace App\Observers;

use App\Models\Blog;
use Illuminate\Support\Str;

class BlogObserver
{
    public function creating(Blog $blog)
    {
        $blog->slug = Str::slug($blog->title);
    }
    public function created(Blog $blog): void
    {
        $blog->unique_id = 'PR-'.$blog->id;
        $blog->save();
    }

    public function updated(Blog $blog): void
    {
        //
    }

    public function deleted(Blog $blog): void
    {
        //
    }

    public function restored(Blog $blog): void
    {
        //
    }

    public function forceDeleted(Blog $blog): void
    {
        //
    }
}

Conclusion

Last of all we can say that, Laravel Observers can help us write cleaner, more maintainable code by separating your application's business logic from your Eloquent models, and providing automatic event handling for common tasks. Which also helps us to keep our controller/repository to be clean.

 

So, it's time to say goodbye. We saw the usage of Laravel Observer class in this chapter. And yes keep up to date with the github repository. That's it for today. See you in my next chapter. Happy coding ๐Ÿ™‚.