Last active
August 29, 2015 14:05
-
-
Save garagesocial/15f7acaa376691b203c6 to your computer and use it in GitHub Desktop.
Laravel Eloquent Helper - Delete Cascade Relations
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 DeleteCascadeTrait | |
* | |
* Simplify the process of delete cascade in eloquent. | |
* | |
* use DeleteCascadeTrait; | |
* public static function getDeleteCascadeRelations() { return array('myrelation'); } | |
*/ | |
trait DeleteCascadeTrait | |
{ | |
/** | |
* PHP does not like abstract static functions | |
* http://stackoverflow.com/questions/999066/why-does-php-5-2-disallow-abstract-static-class-methods | |
* | |
* @return array | |
*/ | |
public static function getDeleteCascadeRelations() | |
{ | |
return array(); | |
} | |
public static function bootDeleteCascadeTrait() | |
{ | |
static::deleting([static::class, "removeCascadeRelations"]); | |
} | |
final public static function removeCascadeRelations($obj) | |
{ | |
foreach ($obj->getDeleteCascadeRelations() as $key) { | |
foreach ($obj->$key()->get() as $relation) { | |
if($relation) { | |
$relation->delete(); | |
} | |
} | |
} | |
} | |
} |
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 User extends Eloquent | |
{ | |
use DeleteCascadeTrait; | |
public static function getDeleteCascadeRelations() | |
{ | |
return array('comments'); | |
} | |
public function comments() | |
{ | |
return $this->hasMany('Comment'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment