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.
Using FTP and PHP to get an array of file details such as size and…
Creating and using Laravel form requests to create cleaner code, separation and reusability for your…
Improving the default Laravel login and register views in such a simple manner but making…
Laravel validation for checking if a field value exists in the database. The validation rule…