In this episode, we dive into how to handle validation inside controller actions, focusing on using the Laravel Actions package. Initially, we look at a situation where validation isn't yet present—if we try to create a resource without filling in required fields, we get an SQL error because nothing stops us.
To fix this, we move the validation logic into the action itself by creating a rules
method that returns an array of rules (much like standard Laravel validation). For example, we add a required
rule for the body
field, ensuring users can't skip it.
We see how adding this method lets Laravel Actions automatically handle request validation. If we try to create a post without the required fields now, we'll get a proper validation error instead of a cryptic SQL error.
The episode also shows how to customize validation messages by implementing a getValidationMessages
method, returning specific error texts for each field. Just like in typical Laravel form requests or Livewire, this gives us control over what the user sees if they break a validation rule.
By the end, we've refactored our action to act pretty much like a controller—fully equipped with validation rules and custom messages, making sure the user experience is clear and informative. If you've used Laravel validation elsewhere, this should feel right at home.