Created
August 9, 2012 15:27
-
-
Save spencerdeinum/3305110 to your computer and use it in GitHub Desktop.
Soft Delete example for Laravel
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
<?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; | |
} | |
} | |
} |
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
<?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