< Back to Posts

Future SoftDeletes Trait in Laravel 8

Richard

#websites


Laravel provides the built-in feature that allows us to flag database rows as deleted without physically deleting them from the database. The issue with this feature is that it only returns rows where deleted_at is null.


We have been working on a project where the database rows are managed by an already built application developed in Filemaker. When a row is created inside Filemaker, instead of the deleted_at date field being set to null, the value is set to 3001-12-31  00:00:00 (aka ridiculous date in the future). When querying the table/model, these rows are not returned.


I have developed a Laravel trait that extends the Laravel built-in SoftDeletes trait to support dates that are set in the future. This may work on older versions of Laravel, we have only tested it on version 8.


Feel free to use the below code and leave a comment at the bottom of this post :)


app/Traits/FutureSoftDeletesScope.php

namespace App\Traits;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletingScope;

class FutureSoftDeletesScope extends SoftDeletingScope {
  public function apply(Builder $builder, Model $model)
  {
      $model = $builder->getModel();
      $builder->where(function($query) use ($model) {
          $query->where($model->getDeletedAtColumn(), '>=', Carbon::now())
          ->orWhere($model->getDeletedAtColumn(), '0000-00-00 00:00:00')
          ->orWhereNull($model->getDeletedAtColumn());
      });
      $this->extend($builder);
  }
}

app/Traits/FutureSoftDeletesTrait.php

namespace App\Traits;

trait FutureSoftDeletesTrait {
  public static function bootFutureSoftDeletesTrait()
  {
      static::addGlobalScope(new FutureSoftDeletesScope);
  }
}

Now at the top of your model add the following:

use FutureSoftDeletesTrait;

Happy coding...

Let's make something great together!

If you'd like to discuss your next project with us, please feel free to give us a call on 01827 781 311 or press the "Start My Project" button to get in touch for a quick quote.

Start My Project