PHP
React to Eloquent Model Lifecycle Events
Implement logic that triggers automatically when Eloquent models are created, updated, deleted, or restored, using model events or dedicated observers.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = ['title', 'content', 'slug'];
protected static function booted(): void
{
// Option 1: Using model's booted method for simple events
static::creating(function (Post $post) {
$post->slug = \Illuminate\Support\Str::slug($post->title);
// You could also send a notification, log, etc.
});
static::updated(function (Post $post) {
// Invalidate cache for this post
\Illuminate\Support\Facades\Cache::forget('post_' . $post->id);
});
// Option 2: Using an Observer (for more complex or shared logic)
// php artisan make:observer PostObserver --model=Post
// In App/Providers/EventServiceProvider.php: Post::observe(PostObserver::class);
}
}
// Example PostObserver.php (not part of the main snippet, but for context)
/*
namespace App\Observers;
use App\Models\Post;
class PostObserver
{
public function creating(Post $post): void
{
$post->slug = \Illuminate\Support\Str::slug($post->title);
}
public function updated(Post $post): void
{
\Illuminate\Support\Facades\Cache::forget('post_' . $post->id);
}
}
*/
How it works: Eloquent models dispatch several events (e.g., `creating`, `created`, `updating`, `updated`, `deleting`, `deleted`, `restoring`, `restored`) at various points in their lifecycle. You can hook into these events directly within the model's `booted` method using static event listeners, or by registering dedicated Observer classes. Observers are ideal for grouping related event listeners into a single class, providing a cleaner and more maintainable way to manage complex logic tied to model events.