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();
});
}
}
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.
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
}
}
}
As of Laravel 5.6, the SoftDeletes trait now fires a forceDeleted
model event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With