Search code examples
laraveleloquentsoft-delete

Is it possible to perform "future" soft delete in laravel?


I found that the soft-delete in laravel Eloquent ORM is just replacing the null in deleted_at column by a timestamp. When querying a table with soft delete, is it just checking if the deleted_at is null, or it is really comparing the value with current time?

I am asking to see if I am able to do schedule delete by setting a future time on the deleted_at column.


Solution

  • Laravel only checks if deleted_at is not NULL. SoftDeletingScope:

    public function apply(Builder $builder)
    {
        $model = $builder->getModel();
    
        $builder->whereNull($model->getQualifiedDeletedAtColumn());
    
        $this->extend($builder);
    }
    

    You can change that by creating your own SoftDeletingScope and SoftDeletingTrait (it's called SoftDeletes in Laravel 5).

    trait MySoftDeletingTrait {
        use Illuminate\Database\Eloquent\SoftDeletingTrait;
    
        public static function bootSoftDeletingTrait()
        {
            static::addGlobalScope(new MySoftDeletingScope);
        }
    }
    

    And

    class MySoftDeletingScope extends Illuminate\Database\Eloquent\SoftDeletingScope {
        public function apply(Builder $builder)
        {
            $model = $builder->getModel();
    
            $builder->where($model->getQualifiedDeletedAtColumn(), '<=', Carbon::now());
    
            $this->extend($builder);
        }
    }
    

    Note that to be able to remove the scope (the remove() method) you would have to override more of the original scope class. At least also isSoftDeleteConstraint, but I'll leave that to you.

    Finally you only have to switch out the trait that you use in your models:

    use MySoftDeletingTrait;