Categories: Development

Hooking into Laravel eloquent events with booted

If you ever need to do an action every time a resource is created or updated or even deleted in Laravel you will need to use the booted method.

In older versions of Laravel the booted method was actually called boot.

The booted function goes into your models class and automatically gets called with the events as specified inside.

The events

Here are the events you can hook into: retrieved,creating,created,updating,updated,saving,saved, deleting,deleted,trashed,forceDeleting,forceDeleted,restoring, restored and replicating.

They are mostly self-explanatory, creating,updating and deleting are what happens before created, updated and deleted.

In the example below you can see that the user_id is automatically filled which saves having to add this each time when doing the Post create method.

You can also easily do logging for the events or run custom functions for certain events.

class Post extends Model
{
    use HasFactory;

    protected static function booted(): void
    {
        static::creating(function (Post $post) {
            $post->user_id = \Auth::id();
        });

        static::created(function (Post $post) {
            Log::debug("Created post {$post->id}");
        });

        static::updated(function (Post $post) {
            Log::debug("Updated post {$post->id}");
        });

        static::deleted(function (Post $post) {
            Log::debug("Deleted post");
        });

    }

}

 

It is very straightforward, helps keep the controller clean and the reduction of repeated code.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago