Laravel 9 Model Observer Tutorial with Example

Laravel Model Observer Example; In this tutorial you will learn how to use and fire model observer in laravel application example. We already explained Laravel Model Events Tutorial with Example and observers in previous example.

Laravel Observers are used to group event listeners for a model eloquent. Laravel Observers will listener event for model eloquent method like create, save, update and delete.

Laravel gives us more events if our model is create or update or any event is fired just like creating, updating, deleting, created, updated, deleted etc more events list are showing below.

List of Laravel Model Events

Here the list of all laravel model events:

  • creating: call before creating a record
  • created: Call after creating a record
  • saving: Call before creating or updating a record
  • updating: Call before updating a record
  • updated: Class after updating a record
  • deleting: Call before deleting a record
  • deleted: Call after deleting a record
  • retrieved: Call after getting data from the database
  • saved: Call after creating or updating a record
  • restoring: Call before restoring a record
  • restored: Call after restoring a record
  • replicating: Call on replicate record

Define Events in Model

Your model will be something like this:

app\Models\Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
    protected $fillable = [
        'title', 'description', 'slug', 'unique_id'
    ];
}

Create Observer

Create observers class for Product. So, create bellow command:

php artisan make:observer PostObserver --model=Post

Next, open app/Observers/PostObserver.php file and you can see the observer file something like below:

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

Register Observers in Serviece Provider

Next, Register Observers class on event service provider something like this.

<?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\PostObserver;
use App\Models\Post;
  
class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
    ];
  
    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        Post::observe(PostObserver::class);
    }
}

Add Route

Next, add routes for geneate post slug using the laravel model Observer class:

<?php
  
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
  
Route::get('posts', [PostController::class, 'index']);

Create Controller and Update Code

Next create a controller using the following command:

php artisan make:controller PostController

Now, opent the app/Http/Controllers/PostController.php and put the below code on it;

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

Now, when you create a post then the slug atomatically generated and saved in your database.

I hope you enjoy with laravel model observers example tutorial..

Leave a Comment