Last active
December 14, 2015 06:38
-
-
Save VvanGemert/5043556 to your computer and use it in GitHub Desktop.
Sample how to use soft delete with Eloquent in Laravel PHP framework. Description of how to use can be found in the example.
I've used Laravel 3.2.13.
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 | |
// Extending Eloquent to support Soft Delete | |
abstract class EloquentSoft extends Eloquent { | |
public $soft_deletable = false; | |
public function delete() | |
{ | |
if ($this->exists) | |
{ | |
if ($this->soft_deletable) | |
{ | |
$record = $this->to_array() | |
$record["deleted_at"] = new \DateTime; | |
unset($record["pivot"]); | |
DB::table('deleted_'.$this->table())->insert($record); | |
} | |
$this->fire_event('deleting'); | |
$result = $this->query()->where(static::$key, '=', $this->get_key())->delete(); | |
$this->fire_event('deleted'); | |
return $result; | |
} | |
} | |
public static function restore($id) | |
{ | |
$model = new static(array(), true); | |
if($model->soft_deletable) | |
{ | |
$deleted_record = (array) DB::table('deleted_'.$model->table())->find($id); | |
if(!empty($deleted_record)) | |
{ | |
$this->fire_event('restoring'); | |
unset($deleted_record["deleted_at"]); | |
$result = self::create($deleted_record); | |
DB::table('deleted_'.$model->table())->delete($id); | |
$this->fire_event('restored'); | |
return $result; | |
} | |
} | |
} | |
} | |
?> |
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 | |
// You can use soft delete by adding the file above in your 'libraries' folder | |
// and extend all your models with 'EloquentSoft'. | |
// NOTE: create a duplicate of your table (schema-only) in the database and prefix it with 'deleted_', | |
// also add the deleted_at (datetime) field to this table. | |
// Example Model | |
class Modelname extends EloquentSoft { | |
public $soft_deletable = true; | |
} | |
// In your controller it is very easy to use soft delete. | |
// Soft Delete record | |
Modelname::find(1)->delete(); | |
// Restore soft deleted record | |
Modelname::restore(1); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated the code to allow models with pivot tables be soft deleted.