In this episode, we're taking a deep dive into validating complex array data coming into our application, specifically for notification preferences. Initially, we notice that there's no validation in place, so we set about adding the necessary rules to make sure everything's squeaky clean before we process anything.
First, we explore how to check that the provided notification keys and channel types actually exist in the database. This is important because users can send down anything, and we need to ensure it matches up with valid records. We implement this in a tidy form request to keep our controller nice and neat.
We also talk about using the exists
validation rule and how to use wildcards in our rules like notifications.*
, giving us the flexibility to validate each entry in an array. After getting validation set up, we realize our tests are failing because the database doesn’t have the expected seeded data. So, we write a seeder for notification channels and show different ways to use it in our test setup to ensure our tests have the right baseline data.
Next up, we write additional tests to specifically check that validation fails if invalid channel types or notification ids are sent. Along the way, we hit a tricky situation: validating the keys of an associative array rather than just the values. To solve this, we use Laravel's prepareForValidation
and programmatically merge the keys into the validation data, allowing us to apply validation rules directly to them — pretty neat trick!
By the end, we have robust validation rules for both the array values (channels) and the array keys (notification ids), all backed up by thorough tests. The episode is full of practical approaches (and a few debugging wins and gotchas!) for handling more advanced data validation in Laravel.