How to delete all comments posted in a post in Laravel? Want to delete a post and the same action will delete the comments on that particular post too.
Laravel makes it very simple to do this. The post has a polymorphic relationship with the comments and you can use the function to delete related comments with a click. So whenever you delete any post, the same action will delete the comments too.
Only Owner Can Delete The Post
Code
Here, in the below code commentable_id is a column where thread id is stored. So in the comment table, where thread ids match all comments will have this action.
$delcomment = Comment::where('commentable_id', $thread->id)->delete();
So, first, the thread which is posts will be deleted, and then related comments.
$thread->delete();
$delcomment = Comment::where('commentable_id', $thread->id)->delete();
The full function is here.
/**
* Remove the specified resource from storage.
*
* @param \App\Thread $thread
* @return \Illuminate\Http\Response
*/
public function destroy(Thread $thread)
{
$thread->delete();
$delcomment = Comment::where('commentable_id', $thread->id)->delete();
return redirect()->route('thread.index')->withMessage('Thread and its comments has been deleted !');
}