Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect force delete in model event

I have set up a model event to check when an image is deleted and delete the related image_size model entries. However image uses soft deletes so if it is being soft deleted then I want to soft delete the image_size records but if the image is being hard deleted using forceDelete then I want to hard delete the image_size records. Is there a way to detect what type of delete it is and act accordingly. Here is what I have 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();
        });
    }
}
like image 296
geoffs3310 Avatar asked Jul 08 '15 14:07

geoffs3310


3 Answers

If i remember correctly you have a property on the $image object called forceDeleting.

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

However i think last time i did this was in a few versions back, so not sure if it still works.

like image 104
Björn Avatar answered Oct 09 '22 20:10

Björn


Now forceDeleting is protected (you can't access to value). You need use
$image->isForceDeleting()

When you work with Observers (recommended on 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
        }
    }
}
like image 35
pablorsk Avatar answered Oct 09 '22 20:10

pablorsk


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

like image 42
Trip Avatar answered Oct 09 '22 18:10

Trip