DO NOT USE SELF KEYWORD WITHIN BOOT METHOD
Aug 29, 2024 Copy Link
I have a non-static method called `removeAttachment`
which I invoke when the model's image is gonna updated or the model is being deleted within the `boot`
method:
/**
* Set the model image.
*
* @param \Illuminate\Http\UploadedFile $value
* @return void
*/
public function setImageAttribute($value)
{
self::removeAttachment();
// Update the image...
}
The previous invocation manner operates as planned but when I used it inside the `boot`
method I hit the Non-static method cannot be called statically exception, even though, the `self`
can be used inside the static methods
And then, when I asked the Codeium AI Tool it told me that Laravel tries to invoke that method statically by the Model class itself, not via the current model instance as happened with the image mutator so, I solved this issue using the deleted model instance that Laravel passes to the eloquent events methods:
/**
* Bootstrap the model and its traits.
*
* @return void
*/
public static function boot()
{
parent::boot();
/**
* Remove the attachment when the model is deleting.
*
* @param \App\Models\BaseModel $model
* @return void
*/
static::deleting(fn($model) => $model->removeAttachment());
}