In this episode, we kick off the work needed to support marking a "best answer" on our forum discussions! It's all about setting up the database and relationships so we can pick one post in a discussion as the solution, and highlight it wherever we need.
We start with some quick decisions: should we track the "best answer" on the post itself, or on the discussion? After weighing the options, we go with adding a solution_post_id
to the discussions table, since it's cleaner and gives us more flexibility to access or display the solution from anywhere.
You'll see how to write a migration to add that solution_post_id
as a nullable foreign key (since not every discussion will have a solution right away). We also cover some Laravel quirks—like how to make sure foreign keys work properly even with custom column names, and ensuring that deleting a solution post sets the solution field back to null
.
Once the migration is done, we set up the Eloquent relationship in the Discussion
model, and tweak the discussion resource so that when we're displaying a discussion, we can also show its solution post if it exists. You'll also see how to eager load the relationship for efficient queries.
Finally, we make sure that only the user who owns the discussion can mark a post as the best solution by tweaking the policy. There's a quick preview in the UI so you can see where the button will go. At the end, we're all set up to move on to the fun part—actually toggling the best answer from the interface! That's coming next episode.