确定是否是事件处理程序Laravel中的软删除


Determine if is a soft delete in a event handler Laravel

我有这个事件处理程序:

protected static function boot() {
    parent::boot();
    static::deleting(function($user) { // before delete() method call this
        $user->comments()->delete();
    });
}

当我使用$user->forceDelete();$user->delete();时,会触发此事件并删除所有注释。这不好,因为我希望此事件仅在$user->forceDelete();上触发。在我的情况下,其他表没有实现软删除的

您可以检查模型上的forceDeleting属性。如果您正在执行forceDelete ,这将被设置(并且为true)

static::deleting(function($user) { // before delete() method call this
    if ($user->forceDeleting) {
        $user->comments()->delete();
    }
});

在模型类中(例如):

public static function boot() {
    
    parent::boot();
    
    static::created(function($item){
        Log::info("Model Created:".get_class($item)."-ID-".$item->id.'-by user: '.Auth::id());
    });
    
    static::updated(function($item){
        Log::info("Model Updated:".get_class($item)."-ID-".$item->id.'-by user: '.Auth::id());
    });
    
    static::deleted(function($item){
        Log::info("Model Soft Delete:".get_class($item)."-ID-".$item->id.'-by user: '.Auth::id());
    });
    static::forceDeleted(function($item){
        Log::info("Model Force Delete:".get_class($item)."-ID-".$item->id.'-by user: '.Auth::id());
    });
    
}