In this episode, we wrap up our new discussion form by adding both validation and authorization. The cool thing is that even though everyone can create a discussion right now (as long as they're signed in), we set up the structure for authorization in case we want to restrict this later.
First, we focus on making sure the form fields are properly validated. We head over to our form and update the wording on our button to say "Start Discussion" to make things a bit clearer. Then, we dive into creating a custom form request, where we define validation rules: the title is required and has a max length, the body is required, and the topic ID is not only required but must exist in the topics table. This ensures that only valid data gets through and we display helpful validation errors to users if something’s wrong.
Next, we get the groundwork ready for proper authorization. We create a policy for our Discussion model and register it in the auth service provider. For now, the policy just returns true
(everyone can post), but this sets us up to easily add more sophisticated rules later. We then test this out to see that everything works—if we switch the policy to return false
, unauthorized users are blocked from creating discussions.
By the end of the episode, we have both validation and an extendable authorization system in place for discussions. This lays the foundation for more advanced features like editing discussions or marking best answers in the future.