Created
September 16, 2015 13:13
-
-
Save damienwebdev/6c4b6461494331eb9cac to your computer and use it in GitHub Desktop.
This file contains hidden or 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
trait ExpiredPosting { | |
/** | |
* Boot the soft deleting trait for a model. | |
* | |
* @return void | |
*/ | |
public static function bootExpiredPosting() | |
{ | |
static::addGlobalScope(new ExpiredPostingScope); | |
} | |
/** | |
* | |
* Get the name of the column for applying the scope. | |
* | |
* @return string | |
*/ | |
public function getPostEndingAtColumn() | |
{ | |
return defined('static::POST_ENDING_AT_COLUMN') ? static::POST_ENDING_AT_COLUMN : 'post_ending_at'; | |
} | |
/** | |
* Get the fully qualified column name for applying the scope. | |
* | |
* @return string | |
*/ | |
public function getQualifiedPostEndingAtColumn() | |
{ | |
return $this->getTable().'.'.$this->getPostEndingAtColumn(); | |
} | |
/** | |
* Get a new query builder that includes soft deletes. | |
* | |
* @return \Illuminate\Database\Eloquent\Builder|static | |
*/ | |
public static function withExpired() | |
{ | |
return (new static)->newQueryWithoutScope(new ExpiredPostingScope()); | |
} | |
} | |
This file contains hidden or 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
class ExpiredPostingScope implements ScopeInterface { | |
/** | |
* Apply the scope to a given Eloquent query builder. | |
* | |
* @param \Illuminate\Database\Eloquent\Builder $builder | |
* @param \Illuminate\Database\Eloquent\Model $model | |
* @return void | |
*/ | |
public function apply(Builder $builder, Model $model) | |
{ | |
$column = $model->getQualifiedPostEndingAtColumn(); | |
$builder->where($column,">=", Carbon::now()); | |
} | |
/** | |
* Remove the scope from the given Eloquent query builder. | |
* | |
* @param \Illuminate\Database\Eloquent\Builder $builder | |
* @param \Illuminate\Database\Eloquent\Model $model | |
* @return void | |
*/ | |
public function remove(Builder $builder, Model $model) | |
{ | |
$column = $model->getQualifiedPostEndingAtColumn(); | |
$query = $builder->getQuery(); | |
foreach ((array) $query->wheres as $key => $where) | |
{ | |
if($where['column'] == $column){ | |
unset($query->wheres[$key]); | |
$query->wheres = array_values($query->wheres); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment