I have made a blogging application in Laravel 8. I am currently working on giving any authenticated user to delete his/her comments.
Deleting comments works fine but, since comments have replies, I run into a problem with deleting replies along with a comment.
In comments-list.blade.php
, I have the delete comment form:
@if ($comment->user->id == Auth::user()->id)
<form class="commentDeleteForm" onsubmit="return confirm('Delete this comment?')" method="post" action="{{ route('comment.delete', $comment->id) }}" novalidate>
@csrf
<button type="submit" class="comment-delete-btn">
<i class="fa fa-trash"></i>
Delete
</button>
</form>
@endif
In the controller, I had:
public function delete_comment($id) {
$comment = Comment::find($id);
if($comment->user_id === auth()->user()->id) {
$comment->delete();
return redirect()->back()->with('success', 'The comment was deleted');
}
}
But, in order to delete replies too, I changed $comment->delete()
to $comment->delete()->with('replies')
.
This change causes a failure to delete the targeted comment, with the error:
Call to a member function with() on bool
@ajax30 You are deleting the comment first and then you are trying to delete replies of comment which you have already deleted.
Here is the updated delete comment function function
public function delete_comment($id) {
$comment = Comment::find($id);
if($comment->user_id === auth()->user()->id) {
$comment->replies()->delete();
$comment->delete();
return redirect()->back()->with('success', 'The comment was deleted');
}
}
I assume you have already created a hasMany relationship of replies in the Comment modal.
Thanks!
Please try answering this question too. Thanks!
(Link removed)
@ajax30 people can answer other questions if they have the time and know the answer. It is not wanted to ask them from one thread to answer another one.
Please consider posting an answer to this question too. Thanks!
(mention and link removed)
@ajax30 as mentioned earlier please don't ask people to answer other threads. They will see it if they have time.
If they are 100% related I can understand it but that isn't the case.
I hope this is clear to you now :)
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community