Kites
Kites

Reputation: 25

How to delete multi relationship Model in Laravel 5.5

I have 3 tables

books: - id - name - deleted_at

posts: - id - book_id - connent - deleted_at

comments: - id - post_id - comment - deleted_at

A book has many posts, a post has many comments.

I want to delete posts and comments relate to a book when I delete the book. I already add relationship in all Models, all table use SoftDelete, and try to use Event in Laravel

// Book Model
protected static function boot() {
    parent::boot();
    static::deleting(function($book) {
         $book->posts()->delete();
    });
}

// Post Model
protected static function boot() {
    parent::boot();
    static::deleting(function($post) {
         $post->comments()->delete();
    });
}

When I try to delete a book:

$book = Book:find($bookId);
$book->delete()

Book and Posts, deleted, but Comments are not deleted. Could I delete comments with Laravel Event? Thank for readding!

Upvotes: 1

Views: 5262

Answers (3)

Daan
Daan

Reputation: 598

You could use this neat little trait made by michaeldyrynda, called laravel-cascade-soft-deletes.

Sample code from the GitHub readme:

<?php

namespace App;

use App\Comment;
use Iatstuti\Database\Support\CascadeSoftDeletes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes, CascadeSoftDeletes;

    protected $cascadeDeletes = ['comments'];

    protected $dates = ['deleted_at'];

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}    

Upvotes: 0

user320487
user320487

Reputation:

You should set your model relationships ON DELETE trigger to CASCADE. Otherwise you'll need to iterate the related records and individually delete them.

$model->related->each(function ($related) { $related->delete(); });

Edit: you have the right idea with model events, but delete posts first and work backwards to books

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

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

Make sure your models all have the soft delete trait and date properties:

 use SoftDeletes;
protected $dates = ['deleted_at'];

Upvotes: 0

plmrlnsnts
plmrlnsnts

Reputation: 1684

You are passing a different variable inside the delete event of your Post model.

// Post Model
protected static function boot() {
    parent::boot();
    static::deleting(function($post) {
         // $book->comments()->delete();
         $post->comments()->delete();
    });
}

Upvotes: 1

Related Questions