PHP
Leveraging Eloquent Model Events for Side Effects
Leverage Laravel Eloquent model events (e.g., `creating`, `updated`, `deleted`) to execute custom logic automatically at different stages of a model's lifecycle.
<?php
// app/Models/Product.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
class Product extends Model
{
protected $fillable = ['name', 'price', 'stock'];
protected static function booted()
{
static::creating(function (Product $product) {
// Auto-set a slug before a product is created
$product->slug = \Illuminate\Support\Str::slug($product->name);
Log::info("Creating product: {$product->name}");
});
static::updated(function (Product $product) {
// Log changes after a product is updated
Log::info("Product updated: {$product->id} - {$product->name}");
// You might trigger a cache invalidation here
});
static::deleted(function (Product $product) {
// Perform cleanup, e.g., delete related files or clear cache
Log::warning("Product deleted: {$product->id} - {$product->name}");
});
static::retrieved(function (Product $product) {
// Perform actions after a model is retrieved from the database
// For example, initialize a calculated attribute
$product->is_expensive = $product->price > 1000;
});
}
}
// Example Usage (e.g., in a controller or test):
$product = Product::create(['name' => 'New Gadget', 'price' => 299.99, 'stock' => 10]);
// The 'creating' event fired and set the slug, and logged.
$product->price = 329.99;
$product->save();
// The 'updated' event fired and logged the change.
$product = Product::find(1); // 'retrieved' event fires
// $product->is_expensive is now set
$product->delete();
// The 'deleted' event fired and logged the deletion.
How it works: Eloquent model events provide hooks into various stages of a model's lifecycle, such as `creating`, `created`, `updating`, `updated`, `deleting`, `deleted`, `retrieved`, etc. By defining these static methods within a model's `booted()` method, you can execute custom logic whenever these events occur. This is invaluable for tasks like automatically generating slugs, invalidating cache, auditing changes, sending notifications, or performing related cleanup operations, keeping your business logic cleanly separated from your controllers or services.