← Back to all snippets
PHP

Automating Actions with Eloquent Model Events

Respond to Eloquent model lifecycle events like `created`, `updated`, or `deleted` to automate tasks, log changes, or invalidate caches, enhancing application logic.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Product extends Model
{
    protected $fillable = ['name', 'price', 'description'];

    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        // Invalidate cache when a product is created or updated
        static::created(function (Product $product) {
            Cache::forget('all_products');
            // Optionally send a notification or log action
            // Log::info('Product ' . $product->id . ' created.');
        });

        static::updated(function (Product $product) {
            Cache::forget('all_products');
            // Optionally update search index
            // $product->updateSearchIndex();
        });

        static::deleted(function (Product $product) {
            Cache::forget('all_products');
            // Handle related data cleanup
            // $product->images()->delete();
        });
    }
}
How it works: Eloquent model events (like `created`, `updated`, `deleted`, `saving`, `deleting`, etc.) allow you to hook into various points of a model's lifecycle and perform actions automatically. This snippet shows how to invalidate a cache whenever a `Product` model is created, updated, or deleted. Events are a powerful way to decouple business logic, ensuring that certain actions (e.g., sending emails, logging, updating search indexes, cleaning up related data) are executed whenever a model changes state, without cluttering controllers or services.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs