Laravel 10 Model Observers Example

In Laravel, model observers allow you to listen to various events triggered by your Eloquent models, such as when a model is created, updated, deleted, or retrieved. Observers provide a convenient way to centralize and organize the logic related to these events.

let's see how to create observers class and how it will works:

app/Models/Product.php

<?php
  
    namespace App\Models;
      
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
      
    class Product extends Model
    {
        use HasFactory;
      
        protected $fillable = [
            'name', 'price', 'slug', 'unique_id'
        ];
    }

For Create observers class of Product Model Run Below Command,

php artisan make:observer ProductObserver --model=Product

app/Observers/ProductObserver.php

<?php
  
    namespace App\Observers;
      
    use App\Models\Product;
      
    class ProductObserver
    {
      
        /**
         * Handle the Product "created" event.
         *
         * @param  \App\Models\Product  $product
         * @return void
         */
        public function creating(Product $product): void
        {
            $product->slug = \Str::slug($product->name);
        }
      
        /**
         * Handle the Product "created" event.
         *
         * @param  \App\Models\Product  $product
         * @return void
         */
        public function created(Product $product): void
        {
            $product->unique_id = 'PR-'.$product->id;
            $product->save();
        }
      
        /**
         * Handle the Product "updated" event.
         *
         * @param  \App\Models\Product  $product
         * @return void
         */
        public function updated(Product $product): void
        {
              
        }
      
        /**
         * Handle the Product "deleted" event.
         *
         * @param  \App\Models\Product  $product
         * @return void
         */
        public function deleted(Product $product): void
        {
              
        }
      
        /**
         * Handle the Product "restored" event.
         *
         * @param  \App\Models\Product  $product
         * @return void
         */
        public function restored(Product $product): void
        {
              
        }
      
        /**
         * Handle the Product "force deleted" event.
         *
         * @param  \App\Models\Product  $product
         * @return void
         */
        public function forceDeleted(Product $product): void
        {
              
        }
    }

Register Observers class in provider.

app/Providers/EventServiceProvider.php

<?php
  
    namespace App\Providers;
      
    use Illuminate\Auth\Events\Registered;
    use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
    use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
    use Illuminate\Support\Facades\Event;
    use App\Observers\ProductObserver;
    use App\Models\Product;
      
    class EventServiceProvider extends ServiceProvider
    {
        /**
         * The event to listener mappings for the application.
         *
         * @var array>
    
         */
        protected $listen = [
            Registered::class => [
                SendEmailVerificationNotification::class,
            ],
        ];
      
        /**
         * Register any events for your application.
         */
        public function boot(): void
        {
            Product::observe(ProductObserver::class);
        }
      
        /**
         * Determine if events and listeners should be automatically discovered.
         */
        public function shouldDiscoverEvents(): bool
        {
            return false;
        }
    }

Create Route:

routes/web.php

<?php
  
    use Illuminate\Support\Facades\Route;
      
    use App\Http\Controllers\ProductController;
      
    /*
    |--------------------------------------------------------------------------
    | Web Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register web routes for your application. These
    | routes are loaded by the RouteServiceProvider within a group which
    | contains the "web" middleware group. Now create something great!
    |
    */
      
    Route::get('product', [ProductController::class, 'index']);

Create Controller

app/Http/Controllers/ProductController.php

<?php
  
    namespace App\Http\Controllers;
      
    use App\Models\Product;
    use Illuminate\Http\Request;
      
    class ProductController extends Controller
    {
        /**
         * Display a listing of the resource.
         *
         * @return \Illuminate\Http\Response
         */
        public function index()
        {
      
            $product = Product::create([
                'name' => 'Platinum 1',
                'price' => 10
            ]);
      
         
        }
    }

Now you can run project and see in your database Entry.