In this episode, we focus on improving how solutions are marked in a discussion-based app. We start by recognizing a potential issue: someone could attempt to mark a post as the solution for a discussion, even if that post doesn't actually belong to the discussion. Clearly, that's not what we want!
To fix this, we first try a quick-and-dirty if-statement check to see if the post belongs to the discussion, but quickly realize that's not the best way to do it. Instead, we improve our code and make use of Eloquent relationships: we use $discussion->posts()->find($postId)
to guarantee we're only ever marking posts that actually belong to the discussion.
We also touch on validation—making sure the post ID actually exists in the database, and handling special cases like unmarking a solution (which should allow a null value). Finally, after some testing, we confirm that the feature now works exactly as expected, and users won't accidentally (or maliciously) mark posts from other discussions as a solution.
By the end of the episode, we've made the solution marking safer and more robust, thanks to clever use of relationships and validation.