A bootable model in Laravel is a model that contains boot methods, which are
methods that are automatically called by Laravel during the model's
lifecycle events. These methods are used to add additional functionality to
the model, such as setting default attribute values or registering event
listeners.
The bootable model feature is a powerful tool that allows developers to
extend and customize model behavior in a flexible and maintainable way. By
defining boot methods in a model, developers can centralize and encapsulate
model-related logic, making their code more organized and easier to
maintain.
Using boot method
Suppose you have a HasImage trait that relates to an image for each model, and you want to delete the image automatically when the model is deleted. In this case, you can add a boot() method to the trait.
public static function boot()
{
// Delete associated images if they exist.
static::deleting(function ($model) {
$model->image->delete();
});
}
The static boot() method is executed automatically when a model is created, making it an excellent location to add custom behavior or event bindings. In this case, we can use the boot() method to delete an associated image whenever a model is deleted.
If the parent model already has a boot() method, using the boot() method in the trait can cause conflicts. To avoid this issue, we can use a different method name, such as bootHasImage(), for the trait's boot method.
Using bootable trait
Example of using bootable trait, as you can see we can use the same method name in the trait, because the trait is not a model.
trait HasImage
{
public static function bootHasImage()
{
// Delete associated images if they exist.
static::deleting(function($model) {
$model->image->delete();
});
}
public function image()
{
return $this->belongsTo(Image::class);
}
}