Get fresh content from StatelyWorld

Laravel’s Eloquent ORM offers a powerful feature set to hook into a model’s lifecycle using events like creating, updating, deleting, and more. Understanding and using these events
helps you write cleaner, more maintainable code while keeping business logic organized within the model itself.

Lifecycle Hooks: boot() vs booted()

boot()

This static method is triggered early when the model is initializing. It’s commonly used to register model events or apply global scopes.

protected static function boot()
{
    parent::boot();

    static::creating(function ($model) {
        // Set default values
    });
}

booted()

This method is executed after the model has been fully booted. It’s ideal for clean separation of concerns when
registering model events.

protected static function booted()
{
    static::created(function ($model) {
        // Log or notify
    });
}

Eloquent Model Events

Here’s a list of all available model events and when they are triggered:

Event When it fires Common Use
retrieved After fetching from DB Log or audit access
creating Before insert Set defaults, validate
created After insert Send welcome email
updating Before update Audit or validate change
updated After update Log changes
saving Before insert or update Universal validator
saved After insert or update Clear cache
deleting Before delete Cascade deletes
deleted After delete Log or notify
restoring Before soft-delete restore Authorization checks
restored After restore Reinitialize state

Preventing Operations Using Events

You can cancel specific operations (like preventing delete) by returning false from an event handler:

static::deleting(function ($model) {
    if ($model->is_locked) {
        return false;
    }
});

This works with creating, updating, deleting, and restoring.

Full Event Template for Your Model

Here’s a practical event registration setup to use inside your Eloquent model:

protected static function booted()
{
    static::creating(function ($model) {
        //
    });

    static::created(function ($model) {
        //
    });

    static::updating(function ($model) {
        //
    });

    static::updated(function ($model) {
        //
    });

    static::deleting(function ($model) {
        //
    });

    static::deleted(function ($model) {
        //
    });

    static::restoring(function ($model) {
        //
    });

    static::restored(function ($model) {
        //
    });
}

Final Thoughts

Model events are an elegant way to organize business logic around your data. Use them to keep your controllers and services clean, and maintain consistent behavior across your application. Whether you’re auto-generating slugs, sending emails, or enforcing security, Laravel’s model events are your go-to tool.

How to Build and Publish a Laravel Package on Packagist
What is AI & How It Works? A Beginner’s Guide

Share This Post !

Leave A Comment