AVOID USING SELF INSIDE THE BOOT METHOD

Aug 29, 2024

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());
}

AI Assistant

Choose AI provider

Text Tools

Make content clear and easy to read

Ask a Question

Get clear answers based on this content

0/500
Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.