1

I have three models: User has-many Post has-many Comment. When I delete a user, I want all of his related posts to automatically be deleted as well as the comments that are related to these posts. In order to achieve this, I have the following code in User and Post models:

// User
protected static function boot() {
    parent::boot();

    static::deleting(function($user) {
        $user->posts()->delete();
    });
}

// Post
protected static function boot() {
    parent::boot();

    static::deleting(function($post) {
        $post->comments()->delete();
    });
}

When I delete a user, all of his posts get deleted, however, the comments are preserved. Why is this happening?

Alex Lomia
  • 6,705
  • 12
  • 53
  • 87

2 Answers2

1

Have you tried to do next?

// User
protected static function boot() {
    parent::boot();

    static::deleting(function($user) {
        foreach ($user->posts() as $post)
        {
            $post->comments()->delete();
        }            
        $user->posts()->delete();

    });

Btw this should be in database schema on delete cascade and you won't need any model code for deleting childs.

KuKeC
  • 4,392
  • 5
  • 31
  • 60
  • Will try this, but the common sense suggests, that whenever a model is deleted, it's `..::deleting()` method should trigger. I wonder, why this isn't happening. The cascade deleteion requires `InnoDB` to be chosen as a DB engine for every table – Alex Lomia Jun 03 '16 at 17:15
  • Ok try to do that. I updated my answer since you first have to delete all comments and then posts for comments. For deletion you need to go thru all posts in foreach and then delete each comments separated. – KuKeC Jun 03 '16 at 17:24
  • Better if you use database schema, it's faster. I had problems with this code with an error: 'Maximum function nesting level of '100' reached, aborting!' – Sangar82 Jun 03 '16 at 20:40
1

Better if you use the database schema to achieve this. It´s faster and no will have errors of 'maximum function nesting level'

public function up()
{
    Schema::create('comments', function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('post_id');
        $table->string('comment');
    });

    Schema::table('comments', function(Blueprint $table){
        $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
    });
}
Sangar82
  • 5,070
  • 1
  • 35
  • 52
  • I am trying to do this, but keep getting `General error: 1215 Cannot add foreign key` error – Alex Lomia Jun 04 '16 at 10:08
  • 1
    see: http://stackoverflow.com/a/37454021/1171049 You need to run first the post migration and before the comments migration... I Hope it helps – Sangar82 Jun 04 '16 at 14:46