Model events are a feature in Laravel’s Eloquent ORM that allow developers to automatically trigger and execute specific code when models perform operations such as creating, updating, or deleting. By listening to these events, you can inject custom logic into the model’s lifecycle, such as data processing before saving or related operations after deletion.
Laravel provides several built-in model events, including:
Within your model class, you typically override the boot method to register event listeners using static methods. The example below shows how to register multiple events in a User model:
namespace App\Models;
<p>use Illuminate\Database\Eloquent\Model;</p>
<p>class User extends Model<br>
{<br>
protected $fillable = ['name', 'email', 'password'];</p>
{
parent::boot();
static::creating(function ($model) {
// Code to execute before creating a user
});
static::created(function ($model) {
// Code to execute after creating a user
});
static::updating(function ($model) {
// Code to execute before updating a user
});
static::updated(function ($model) {
// Code to execute after updating a user
});
static::deleting(function ($model) {
// Code to execute before deleting a user
});
static::deleted(function ($model) {
// Code to execute after deleting a user
});
}
}
This method makes it easy to insert business logic and automate complex operations.
The code inside an event listener is where you put your custom business logic. For example, use the creating event to automatically capitalize the first letter of a user’s name:
namespace App\Models;
<p>use Illuminate\Database\Eloquent\Model;</p>
<p>class User extends Model<br>
{<br>
protected $fillable = ['name', 'email', 'password'];</p>
{
parent::boot();
static::creating(function ($model) {
$model->name = ucfirst($model->name);
});
}
}
With this, whenever a user model is about to be created, the first letter of the name attribute is automatically capitalized to ensure consistent data formatting.
Model events have a wide range of practical applications:
This article introduced the basic concepts and usage of model events in Laravel. By leveraging event listeners, developers can run custom logic at critical points in the model lifecycle, improving modularity and maintainability of their code. Flexible use of model events helps build more efficient and clear business workflows.
Mastering model events will boost your Laravel development efficiency while ensuring your application’s scalability and stability. We hope this guide helps you better understand and apply Laravel model events to your web projects.