PHP
Triggering Actions with Eloquent Model Events
Learn how to utilize Laravel Eloquent model events to execute custom logic automatically when models are created, updated, deleted, or other lifecycle actions occur.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
/**
* The "booted" method of the model.
*/
protected static function booted()
{
static::created(function (Product $product) {
// Perform action after a product is created
// e.g., Log activity, send notification, update cache
logger('Product ' . $product->name . ' (ID: ' . $product->id . ') was created.');
});
static::updated(function (Product $product) {
// Perform action after a product is updated
logger('Product ' . $product->name . ' (ID: ' . $product->id . ') was updated.');
if ($product->isDirty('price')) {
// Price was changed, notify marketing!
// Mail::to('[email protected]')->send(new PriceChangeNotification($product));
}
});
static::deleting(function (Product $product) {
// Perform action BEFORE a product is deleted
// e.g., Delete related files, cascade soft deletes manually
// $product->images()->delete();
});
}
}
// Example usage:
// $product = Product::create(['name' => 'New Gadget', 'price' => 99.99]); // 'created' event fires
// $product->price = 109.99;
// $product->save(); // 'updated' event fires
// $product->delete(); // 'deleting' event fires
How it works: Eloquent model events allow you to hook into various stages of a model's lifecycle, such as `created`, `updated`, `deleted`, `saving`, `retrieved`, etc. By defining static methods like `booted` in your model, you can register closures that will be executed automatically when these events occur. This is incredibly useful for implementing side effects like logging, sending notifications, invalidating cache, or performing data cleanup without cluttering your controllers or services.