Let's assume I have a Book. This Book has Chapters and those Chapters in this Book have Subchapters.
So I have three models:
Book > Chapter > Subchapter
When I delete the Book ($book->delete();), I also want to delete the related Chapters of this Book and also the related Subchapters of all the Chapters from the Book.
Here (Automatically deleting related rows in Laravel (Eloquent ORM)) I found out about Eloquent Events. Whenever a Book is deleted, before that, the Chapter gets deleted because we hook in:
class Book extends Eloquent
{
public function chapters()
{
return $this->has_many('Chapter');
}
protected static function boot() {
parent::boot();
static::deleting(function($book) {
$book->chapters()->delete();
});
}
}
So I thought, I only have to implement the same code in my Chapter-Model, only exchanging "Book" with "Chapter" and "Chapter" with "Subchapter":
class Chapter extends Eloquent
{
public function subChapters()
{
return $this->has_many('SubChapter');
}
protected static function boot() {
parent::boot();
static::deleting(function($chapter) {
$chapter->subChapters()->delete();
});
}
}
This works fine when I delete a Chapter. All the Subchapters will also be deleted.
When I delete the Book it works fine with the Chapters. All the Chapters will also be deleted.
However it only deletes Chapters when I delete the Book. It does not delete the related Subchapters of the deleted Chapters.
Can anybody help me?