Created
March 18, 2014 10:05
-
-
Save itsgoingd/9617096 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
<?php | |
/* Example of a base model, which uses 0 instead of null value of the deleted_at as the deleted state when using soft-delete */ | |
class BaseModel extends \Illuminate\Database\Eloquent\Model | |
{ | |
/** | |
* Get a new query builder for the model's table. | |
* | |
* @param bool $excludeDeleted | |
* @return \Illuminate\Database\Eloquent\Builder|static | |
*/ | |
public function newQuery($excludeDeleted = true) | |
{ | |
$builder = new Builder($this->newBaseQueryBuilder()); | |
// Once we have the query builders, we will set the model instances so the | |
// builder can easily access any information it may need from the model | |
// while it is constructing and executing various queries against it. | |
$builder->setModel($this)->with($this->with); | |
if ($excludeDeleted && $this->softDelete) | |
{ | |
$builder->where($this->getQualifiedDeletedAtColumn(), 0); | |
} | |
return $builder; | |
} | |
/** | |
* Determine if the model instance has been soft-deleted. | |
* | |
* @return bool | |
*/ | |
public function trashed() | |
{ | |
return $this->softDelete && $this->attributes[static::DELETED_AT] != '0000-00-00 00:00:00'; | |
} | |
/** | |
* Restore a soft-deleted model instance. | |
* | |
* @return bool|null | |
*/ | |
public function restore() | |
{ | |
if ($this->softDelete) | |
{ | |
// If the restoring event does not return false, we will proceed with this | |
// restore operation. Otherwise, we bail out so the developer will stop | |
// the restore totally. We will clear the deleted timestamp and save. | |
if ($this->fireModelEvent('restoring') === false) | |
{ | |
return false; | |
} | |
$this->{static::DELETED_AT} = 0; | |
// Once we have saved the model, we will fire the "restored" event so this | |
// developer will do anything they need to after a restore operation is | |
// totally finished. Then we will return the result of the save call. | |
$result = $this->save(); | |
$this->fireModelEvent('restored', false); | |
return $result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Much needed feature but why 0? i know it's intuitive and almost always sufficient but wouldn't minimum value of datetime (
1000-01-01 00:00:00.000000
) make more sense?