In this episode, we're improving the forums by showing a preview of the first post for each discussion in the forum index. This little preview helps users quickly get a sense of what the discussion is about without having to click in.
To start off, we look at how to add a bodyPreview
to our post resource. It's simply the post body, but we make sure to limit its length so it doesn't take up too much space. For this, we use Laravel's string helper to keep things tidy, and then use Tailwind CSS's line clamp utility to visually cap the number of lines it takes up.
Next, we realized that the preview should actually be tied to the post resource (not the discussion resource), since it’s the post that contains the body text. So, we adjust our code and make sure the discussion resource has access to the first post's preview thanks to an existing relationship.
There was a small hiccup when some discussions didn't have any posts, so we walked through adding a test post to keep everything working smoothly. Then, we styled the preview text: lowering its prominence, tweaking the size, and adding some margin. Finally, we fill out the posts with a bit of extra content to show off how the preview works with longer posts.
To keep things neat, we set a character limit for the preview in the backend and use Tailwind’s line-clamp
class to ensure every preview looks consistent, capping the number of display lines (with ellipses if the text overflows). This way, users get a handy snippet from the first post of each discussion right in the index, all managed simply with a bit of backend logic and some handy CSS.