PHP
Leverage Eloquent Model Events for Lifecycle Hooks
Discover how to use Eloquent model events (e.g., creating, updated, deleted) to execute custom logic during a model's lifecycle, like sending notifications or logging.
<?php
namespace App\Observers;
use App\Models\Product;
use Illuminate\Support\Facades\Log;
class ProductObserver
{
/**
* Handle the Product "creating" event.
*
* @param \App\Models\Product $product
* @return void
*/
public function creating(Product $product)
{
// You can modify the product before it's saved for the first time
$product->uuid = (string) \Illuminate\Support\Str::uuid();
Log::info('Product is about to be created: ' . $product->name);
}
/**
* Handle the Product "created" event.
*
* @param \App\Models\Product $product
* @return void
*/
public function created(Product $product)
{
// Send a notification, log activity, etc.
Log::info('New product created: ' . $product->name . ' (ID: ' . $product->id . ')');
// Mail::to($product->user->email)->send(new NewProductNotification($product));
}
/**
* Handle the Product "updating" event.
*
* @param \App\Models\Product $product
* @return void
*/
public function updating(Product $product)
{
// Perform validation or adjust data before update
if ($product->isDirty('price') && $product->price < 0) {
throw new \Exception('Product price cannot be negative.');
}
}
/**
* Handle the Product "updated" event.
*
* @param \App\Models\Product $product
* @return void
*/
public function updated(Product $product)
{
Log::info('Product updated: ' . $product->name . ' (ID: ' . $product->id . ')');
}
/**
* Handle the Product "deleting" event.
*
* @param \App\Models\Product $product
* @return void
*/
public function deleting(Product $product)
{
// Clean up related resources before deletion
// $product->images()->delete();
Log::warning('Product is about to be deleted: ' . $product->name);
}
/**
* Handle the Product "deleted" event.
*
* @param \App\Models\Product $product
* @return void
*/
public function deleted(Product $product)
{
Log::info('Product deleted: ' . $product->name . ' (ID: ' . $product->id . ')');
}
// To register the observer (e.g., in AppServiceProvider's boot method):
// use App\Models\Product;
// use App\Observers\ProductObserver;
// Product::observe(ProductObserver::class);
}
How it works: Eloquent model events provide hooks into a model's lifecycle, allowing you to execute code when models are being `created`, `updated`, `deleted`, and more. Using Observers, as shown, centralizes event-handling logic, making your models cleaner. For example, `creating` can set default values like a UUID, `created` can trigger notifications, and `updating` can validate data before changes are persisted, enhancing application logic and data integrity.