Skip to content

Instantly share code, notes, and snippets.

@angelmartz
Created December 19, 2013 21:17
Show Gist options
  • Select an option

  • Save angelmartz/8046409 to your computer and use it in GitHub Desktop.

Select an option

Save angelmartz/8046409 to your computer and use it in GitHub Desktop.
ugust 23rd 2013
USING LARAVEL 4′S MODEL EVENTS TO CASCADE DELETION
Cascading deletion in Laravel 4 can be accomplished setting up FOREIGN KEY‘s and adding an ->onDelete('cascade') in your Schema.
Read on for an alternative way to cascade a deletion using Events.
Assume you have a Model called Author which has many Books.
class Author extends Eloquent {
public function books()
{
return $this->hasMany('books');
}
}
If you delete an Author instance, you probably want to delete all associated Books as well. This is easily done Using Laravel 4′s Model Events.
class Author extends Eloquent {
public static function boot()
{
parent::boot();
static::deleted(function($author)
{
Book::destroy($author->books()->lists('id'));
});
}
public function books()
{
return $this->hasMany('books');
}
}
The Illuminate\Database\Eloquent\Collection()->lists() method is very useful in this context, as it returns an array of the specified attribute from the Collection.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment