Last active
May 21, 2021 11:52
-
-
Save brendonexus/31d30684825818caefabbb72f7809e8f to your computer and use it in GitHub Desktop.
Laravel deleted_at traits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits; | |
trait FutureSoftDeletesTrait { | |
public static function bootFutureSoftDeletesTrait() | |
{ | |
static::addGlobalScope(new FutureSoftDeletesScope); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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