Skip to content

Instantly share code, notes, and snippets.

@brendonexus
Last active May 21, 2021 11:52
Show Gist options
  • Save brendonexus/31d30684825818caefabbb72f7809e8f to your computer and use it in GitHub Desktop.
Save brendonexus/31d30684825818caefabbb72f7809e8f to your computer and use it in GitHub Desktop.
Laravel deleted_at traits
<?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');
});
$this->extend($builder);
}
}
<?php
namespace App\Traits;
trait FutureSoftDeletesTrait {
public static function bootFutureSoftDeletesTrait()
{
static::addGlobalScope(new FutureSoftDeletesScope);
}
}
<?php
namespace App\Models;
use App\Traits\FutureSoftDeletesTrait;
class Publication extends Model
{
use FutureSoftDeletesTrait;
const DELETED_AT = 'field_name'; //This might not be required if following laravel convensions and using softDeletes in your migrations
public function getDeletedAtColumn() {
return defined('static::DELETED_AT') ? static::DELETED_AT : 'deleted_at';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment