In Laravel, both boot and booted methods are used to hook into the model's lifecycle events, but they serve slightly different purposes and are used in different contexts.
boot Method
The boot method is a static method that is called when the model is first initialized. This is where you can register model event listeners. It is important to call parent::boot() to ensure that any booting logic defined in the parent class is also executed.
Example:
protected static function boot()
{
parent::boot();
static::updated(function ($model) {
// Logic to execute when the model is updated
// lg('model updated','');
});
}
booted Method
The booted method is also a static method, but it is called after the boot method has been executed. This method is useful if you want to ensure that all booting logic has been completed before executing your custom logic.
Example:
protected static function booted(): void
{
static::created(function (User $user) {
// Logic to execute when a new User model is created
// ...
});
}
Key Differences
-
Execution Order:
-
bootis called first when the model is initialized. -
bootedis called after thebootmethod has completed.
-
-
Use Case:
- Use
bootif you need to register event listeners and ensure that the parent class's boot logic is executed. - Use
bootedif you need to perform actions after all booting logic has been completed.
- Use
Which One to Use?
- If you need to register event listeners and ensure that the parent class's boot logic is executed, use the
bootmethod. - If you need to perform actions after all booting logic has been completed, use the
bootedmethod.
In most cases, boot is sufficient for registering model event listeners. However, if you have specific requirements that need to be executed after all booting logic, then booted is the appropriate choice.
Example Usage
Here is an example that demonstrates the use of both methods in a model:
class User extends Authenticatable
{
protected static function boot()
{
parent::boot();
static::updated(function ($model) {
// Logic to execute when the model is updated
// lg('model updated','');
});
}
protected static function booted(): void
{
static::created(function (User $user) {
// Logic to execute when a new User model is created
// ...
});
}
}
In this example, the updated event listener is registered in the boot method, and the created event listener is registered in the booted method. This ensures that the updated event listener is registered as part of the model's initialization process, while the created event listener is registered after all booting logic has been completed.