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.
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.
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Some early September spring shots from a bushwalk, It is still too early for wildflowers.
I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…
If you ever needed a simple solution in Laravel to delete an entire directory and…
How to enforce only one user to register or be registered in a Laravel web…