2

ive implemented nested comments in laravel with parent_id and there's another table votes where related data's are stored.

I've hasMany relation defined in comments model. Now when i delete a comment, it should delete all its replies and votes as well.

To delete votes i used

$review->votes()->delete(); 

which works perfectly. but i'm stuck with deleting votes for nested replies.

If i use foreach loop how to loop inside all levels which is dynamic.

public function deletereview($id=null){

    $review = Review::find($id);

    foreach($review->replies as $reply){
        $reply->votes()->delete();
        //how to do this for all levels?
        $reply = $reply->votes(); // this doesn't work
    }
    return back();
}

Kindly advise on the proper way of doing it.

Note : i've read through the cascade options from migrations but that doesn't explain anything for nested comments(reply of replies and its related data's).

Thanks -Vijay

1
  • Afaik when you delete a comment and have a cascading relationship for its replies and votes, it should delete those as well. Do you have cascading relationships for replies and votes on your comments? Please show us the related migrations. Commented Apr 8, 2019 at 7:21

2 Answers 2

4
// Review Model
public function deleteRelatedData() {

  // Delete all votes of this review
  $this->votes()->delete();

  // Calling the same method to all of the child of this review
  $this->replies->each->deleteRelatedData();
}

// Controller
public function deletereview($id=null){
    $review = Review::find($id);
    $review->deleteRelatedData();
    return back();
}
1
  • Thanks for your answers guys, but i solved it by reducing the reply level to level 1 so which means there needs only one foreach loop. But before that i followed a similar method like yours and solved the issue as well.
    – Vijay
    Commented Apr 9, 2019 at 11:20
0

I would recommend use observer for this.

https://laravel.com/docs/5.8/eloquent#observers

public function deleted(Review $review)
{
    foreach($review->replies as $reply){
    $votes = $reply->votes;
    Votes::destroy($votes)
}

Destroy method allow you to delete multiple models. For any next level you have to use another foreach loop in this case.

$reply = $reply->votes(); doesn't work since you should use

$votes = $reply->votes;
//or
$votes = $reply->votes()->get();

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.