Skip to content

Instantly share code, notes, and snippets.

@garagesocial
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save garagesocial/15f7acaa376691b203c6 to your computer and use it in GitHub Desktop.
Save garagesocial/15f7acaa376691b203c6 to your computer and use it in GitHub Desktop.
Laravel Eloquent Helper - Delete Cascade Relations
<?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();
}
}
}
}
}
<?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