Observer in Laravel

Observer in Laravel is used to do any operations that may be needed before or after any CUD operations on a model. Like before Creating a record, After record is created in the model. Similarly before updating a record and after record is updated etc..  

How to create observer?

> php artisan make:observer ProductObserver –model=Product

If Observers directory is not available already, this command will create Observers directory with in app directory 

Along with this, ProductObserver.php file will be created

App/Observers/ ProductObserver.php

<?php

namespace App\Observers;

use App\Models\Product;

class ProductObserver
{

    /**

     * Handle the Product "creating" event.

     * @param  \App\Models\Product  $product

     * @return void

     */

    public function creating(Product $product): void
    {

        \Log::info("Product is being created: " . $product->name);

    }
    /**
     * Handle the Product "created" event.
     */
    public function created(Product $product): void
    {
        \Log::info("Product is created: " . $product->name);
    }


    /**
     * Handle the Product "updating" event.
     */
    public function updating(Product $product): void
    {
        \Log::info("Product is being updated: " . $product->name);
    }

    /**
     * Handle the Product "updated" event.
     */
    public function updated(Product $product): void
    {
        \Log::info("Product is updated: " . $product->name);
    }

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

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

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

How observer works?

Before events are triggered before database operation. These are

Creating: When a new record is about to be saved

Updating: When an existing record is about to be updated

Deleted: When an existing record is about to be deleted

After events are triggered after db operation is completed.

Created: This is triggered when record is saved in the db

Updated: When record is updated

Deleted: When record deletion is complete

How these actions are triggered?

To trigger these observer events,

go to

app > Providers > AppServiceProvider.php

Assume we need to create Observer for Product model

Open AppServiceProvider.php file, It will look like as shown below

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use App\Models\Product;
use App\Observers\ProductObserver;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        //
    }
}

And it will look as shown below after making changes in it

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use App\Models\Product;
use App\Observers\ProductObserver;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Product::observe(ProductObserver::class);
    }
}

Test the Observer

You can test the observer by creating or updating a product using Tinker or a controller.

Using Tinker:

> php artisan tinker
> use App\Models\Product;
// Create a product
> Product::create(['name' => 'Sample Product', 'stock' => 10]);
// Update the stock
> $product = Product::first();
> $product->update(['stock' => 3]);
 

// Delete the product
> $product->delete();

Log Output:

In the storage/logs/laravel.log, you’ll see:

[INFO] A new product is being created: Sample Product

[INFO] Product created: Sample Product, Stock: 10

[INFO] Stock updated for ‘Sample Product’: Old Stock = 10, New Stock = 3

[WARNING] Low stock alert for ‘Sample Product’: Stock = 3

[INFO] Product deleted: Sample Product

Limitation

Observer works only with Eloquent ORM and not with query builder

Leave a Comment

Your email address will not be published. Required fields are marked *

Share via
Copy link
Powered by Social Snap