Laravel Model Observers Tutorial Example From Scratch

Step 1: Create the application

We need to run command to create Laravel 8 projects.

composer create-project --prefer-dist laravel/laravel laravel_observers
cd laravel_observers

This is the list of all of the events, eloquent model fired that we can hook into

  • retrieved
  • creating
  • created
  • updating
  • updated
  • saving
  • saved
  • deleting
  • deleted
  • restoring
  • restored

Create Migration and put code below.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('price');
            $table->string('slug');
            $table->string('unique_id')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

Run Migrate

php artisan migrate

Create Model

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'
    ];
}

Create observers class for Product. So, create bellow 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)
{
$product->slug = \Str::slug($product->name);
}

/**
* Handle the Product "created" event.
*
* @param \App\Models\Product $product
* @return void
*/
public function created(Product $product)
{
$product->unique_id = 'MAC-'.$product->id;
$product->save();
}

/**
* Handle the Product "updated" event.
*
* @param \App\Models\Product $product
* @return void
*/
public function updated(Product $product)
{

}

/**
* Handle the Product "deleted" event.
*
* @param \App\Models\Product $product
* @return void
*/
public function deleted(Product $product)
{

}

/**
* Handle the Product "restored" event.
*
* @param \App\Models\Product $product
* @return void
*/
public function restored(Product $product)
{

}

/**
* Handle the Product "force deleted" event.
*
* @param \App\Models\Product $product
* @return void
*/
public function forceDeleted(Product $product)
{

}
}

Register Observers class on 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 listener mappings for the application.
*
* @var array
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];

/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
Product::observe(ProductObserver::class);
}
}

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 Route:

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' => 'Mac Book',
            'price' => 50000
        ]);
  
        dd($product);
    }
}

Run server:

php artisan serve
http://127.0.0.1:8002/product

Git: https://github.com/siddharth018/Laravel-8-Model-Observers.git

Leave a Comment