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

Summarize, simplify, and ask questions about this content using your preferred AI provider.

Text Tools

Generate cleaner and easier-to-read versions of this content instantly

Have a Question?

Ask anything related to this content and get a focused AI-generated answer.

0/500
Mahmoud Ramadan
Author

Mahmoud Ramadan

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