-
-
Save davidhemphill/4680622 to your computer and use it in GitHub Desktop.
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 | |
class CustomDeleteModel extends Eloquent | |
{ | |
// Return our custom query any time we run a query from this model | |
protected function query() | |
{ | |
return new CustomDeleteQuery($this); | |
} | |
// Override the delete method with an injection of the time we deletethe row | |
public function delete() | |
{ | |
if( $this->exists ) | |
{ | |
$this->fire_event('deleting'); | |
$time = time(); | |
$result = $this->query()->where(static::$key, '=', $this->get_key())->update(array('deleted_at' => $time)); | |
$this->attributes['deleted_at'] = $time; | |
$this->fire_event('deleted'); | |
return $result; | |
} | |
} | |
// Restore the deleted row | |
public function restore() | |
{ | |
$this->fire_event('restoring'); | |
$result = $this->query()->deleted()->where(static::$key, '=', $this->get_key())->update(array('deleted_at' => null)); | |
$this->attributes['deleted_at'] = null; | |
$this->fire_event('restored'); | |
return $result; | |
} | |
protected function has_one_or_many($type, $model, $foreign) | |
{ | |
return parent::has_one_or_many($type, $model, $foreign)->where_null('deleted_at'); | |
} |
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 | |
use Laravel\Database\Eloquent\Query; | |
class CustomDeleteQuery extends Query | |
{ | |
public function __construct($model) | |
{ | |
// Pass the constructor data | |
parent::__construct($model); | |
// For every query only return results that | |
// have a null value in 'deleted_at' | |
$this->where_null('deleted_at'); | |
} | |
/** | |
* Method to query only deleted items in our query | |
* Usage: Model::where('foo', '=', 'bar')->deleted()->get(); | |
*/ | |
public function deleted() | |
{ | |
// Grab the existing where conditions | |
$wheres = $this->table->wheres; | |
// Apply a filter that will strip out the existing "where_null('deleted_at')" | |
$wheres = array_filter( $wheres, function($where){ | |
if( ! ( $where['type'] == 'where_null' && $where['column'] == 'deleted_at' ) ) | |
{ | |
return $where; | |
} | |
}); | |
// Replace the existing where conditions with the filtered one | |
$this->table->wheres = $wheres; | |
// make sure we grab rows where 'deleted_at' is not null | |
$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