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.