How to detect force removal in a model event

I have set a model event to check when the image is removed and remove the associated image_size model entries. However, the image uses soft deletes, so if it is softly deleted, I want to softly delete the image_size entries, but if the image is hard deleted using forceDelete, I want to delete the image_size entries. Is there a way to determine what type of deletion and proceed accordingly. Here's what I've seen so far in my image model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Image extends Model
{
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['url', 'thumb_url', 'filename'];

    /**
     * Relationship to image sizes
     */
    public function sizes()
    {
        return $this->hasMany('App\Image_size');
    }

    /**
    * Model events
    */
    protected static function boot() {
        parent::boot();

        static::deleting(function($image) { // before delete() method call this
             $image->sizes()->delete();
        });
    }
}

      

+4


source to share


3 answers


If I remember correctly, you have a property on an object $image

named forceDeleting

.

static::deleting(function($image) { 
    if($image->forceDeleting){
        //do in case of force delete
    } else {
        //do in case of soft delete
    }
});

      



However, I think the last time I did this there were multiple versions, so not sure if it still works.

+7


source


Now forceDeleting

protected (you cannot access the value). You need to use
$image->isForceDeleting()

When working with Observers (recommended in Laravel> 5.5).



class Image extends Model
{
    use SoftDeletes;

    /* ... */

    protected static function boot(): void
    {
        parent::boot();
        parent::observe(ImageObserver::class);
    }
}

class ImageObserver
{
    public function deleting($image): void
    {
        if ($image->isForceDeleting()) {
            // do something
        }
    }
}

      

+1


source


As of Laravel 5.6, the SoftDeletes trait now fires a model event forceDeleted

.

0


source







All Articles