How to use Laravel Model Observers, Eloquent Hook giống với wordpress? (ok)

https://www.itsolutionstuff.com/post/how-to-use-laravel-model-observersexample.html

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 orupdated).
Saved: after a record has been saved (either created orupdated).
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 berestored.
Restored: after a soft-deleted record has been restored.

Một ví dụ đã hoàn thành 🌟🌟🌟

C:\xampp\htdocs\test\routes\web.phpC:\xampp\htdocs\test\routes\web.php

<?php
use App\Http\Controllers\HomeController;
use App\Http\Controllers\ProductController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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('/', function () {
  return view('welcome');
});
Auth::routes();
Route::get('/home', [HomeController::class, 'index'])->name('home');
Route::get('product', [ProductController::class, 'index']);

C:\xampp\htdocs\test\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',
  ];
}

C:\xampp\htdocs\test\database\migrations\2022_05_09_183047_create_products_table.php

<?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')->unique();
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('products');
  }
}

Cách đăng ký một observers (trình quan sát) bằng command

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

php artisan make:observer ProductObserver --model=Product

C:\xampp\htdocs\test\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 = 'PR-' . $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) {
    //
  }
}

Cách đăng ký 1 Observers trên provider

php artisan make:provider TestProvider
Và trong C:\xampp\htdocs\test\config\app.php thêm class sau :)
App\Providers\TestProvider::class 😁😁😁😁

Hoặc chúng ta có thể thêm vào class provider có sẵn 👍👍))))

C:\xampp\htdocs\test\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;
// === Thêm 2 dòng này 😒
use App\Models\Product;
use App\Observers\ProductObserver;
class EventServiceProvider extends ServiceProvider {
  /**
   * The event listener mappings for the application.
   *
   * @var array<class-string, array<int, class-string>>
   */
  protected $listen = [
    Registered::class => [
      SendEmailVerificationNotification::class,
    ],
  ];
  /**
   * Register any events for your application.
   *
   * @return void
   */
  public function boot() {
    Product::observe(ProductObserver::class);
  }
}

C:\xampp\htdocs\test\app\Http\Controllers\ProductController.php

<?php
namespace App\Http\Controllers;
use App\Models\Product;
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,
    ]);
    dd($product);
  }
}

Register Observers class on provider.

Hello,

If you need to see example of laravel observers example. We will use how to use laravel model observers. you can understand a concept of what is observers in laravel. this example will help you laravel model observers.

i will explain you how to use laravel model observers event, you can easily use with laravel 6, laravel 7, laravel 8 and laravel 9 project.

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

I will give you very simple definition and use of laravel observers is, when you need to generate slug or auto generate unique id or something like logic add before or after create record then observers will help you. i will give you bellow events that provide by observers and simple example bellow:

Eloquent Hook

  • 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 orupdated).

  • Saved: after a record has been saved (either created orupdated).

  • 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 berestored.

  • Restored: after a soft-deleted record has been restored.

Example:

Now here we will see simple example, i have one product model and it has name, slug, price and unique_id column. so i need to create one record with name an price only. but when it's create i need to generate slug from name and auto generate unique_id.

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

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 = 'PR-'.$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 Demo 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

Read Also: Laravel Eloquent withMin(), withMax() and withAvg() Example

<?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        ]);          dd($product);    }}

now you can run project and see.

it will create record as like bellow:

I hope it can help you...

// Some code

Last updated