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

Share via

Filed in:

Tips Eloquent
Mahmoud Ramadan

Mahmoud Ramadan

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

Most recent

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using...

    FREE

  • What is SQL Injection

    What is SQL Injection

    FREE

  • Leveraging virtual generated columns in MySQL using Laravel

    Leveraging virtual generated col...

    FREE