Update to LaraBlog PackagePar Eric Antoine Scuccimarra
I made an update the other day to the LaraBlog package. I added the ability to reply to comments and for users to delete their own comments. At first I had a hard time figuring out how to display the nested comments, as theoretically you can have an infinite number of replies to a comment, so how do you determine the inset when Bootstrap only has 12 columns?
This was easily resolved by two realizations:
- With Blade includes I can recursively include a template into itself.
- Bootstrap doesn't use 12 absolute size columns, but divides the available space into 12 columns.
So what I did was update my Blog model so that when getting the comments for a blog I only get the original comments, not replies. Then I added to my Comments model a function to get the replies to a specific comment.
I already had my comments display in a separate view which displayed the form to leave a comment and then all of the comments for a specific post. I separated this out into multiple views:
- The old comment view - comments.blade.php - now has the formatting and then includes the _form.blade.php and the comments index view.
- The _form has just the form to submit a comment.
- The comments index loops through the comments and for each:
- Includes the comments show view and...
- Loops through the replies and includes the index for each
- The show.blade.php displays each comment and includes the _form which is hidden until the user clicks on reply.
The index, when including replies, leaves a blank column to the left of the replies, which, when recursively included in the levels of nested replies, will size itself to the available space, so that the indent gets smaller on every nested level of replies - but there could theoretically be an infinite level of nested replies without breaking anything.
I had never thought of recursive including of views until I came across the idea on stack overflow while looking for a solution as to how to address what looked to be a nightmare of infinite nested loops; but that idea provided a simple and elegant solution to what was looking to be a complete mess.