Skip to content

Instantly share code, notes, and snippets.

@spencerdeinum
Created August 9, 2012 15:27
Show Gist options
  • Save spencerdeinum/3305110 to your computer and use it in GitHub Desktop.
Save spencerdeinum/3305110 to your computer and use it in GitHub Desktop.
Soft Delete example for Laravel
<?php
class Softdelete extends HealthieModel
{
protected function query()
{
return new SoftDeleteQuery($this);
}
public function delete()
{
if( $this->exists )
{
$this->fire_event('deleting');
$result = $this->query()->where(static::$key, '=', $this->get_key())->update(array('deleted_at' => time()));
$this->fire_event('deleted');
return $result;
}
}
}
<?php
use Laravel\Database\Eloquent\Query;
class SoftDeleteQuery extends Query
{
public function __construct($model)
{
parent::__construct($model);
$this->where_null('deleted_at');
}
public function deleted()
{
$wheres = $this->table->wheres;
$wheres = array_filter( $wheres, function($where){
if( ! ( $where['type'] == 'where_null' && $where['column'] == 'deleted_at' ) )
{
return $where;
}
});
$this->table->wheres = $wheres;
$this->where_not_null('deleted_at');
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment