Conditionally Add Validation in your Laravel Request Classes
Recently I had to have some seriously advanced requests for one of our clients. Essentially they needed an advertisement platform that would let them specify “shares” for different types of ads on the website.
However, these images needed to be of the correct proportions for the type of ad that was specified, for example, a “ Feature” ad would need to be a square (200x200), and a “ Sidebar” ad would need to be rectangle (100x500).
So what is the “Laravel” way of having conditionals in your request class?
It’s actually relatively simple. Take for example the following request class:
Our initial request class
Ok great, so this looks ok. We’re validating that the placement that has been request is in a certain array, and that the image being passed is, in fact, an image.
The tricky part here is to conditionally add a rule based on the type of placement the user has requested. Out of the box, Laravel has a super handy way of doing this with the override named withValidator
. What this handy method will do is allow us to use closures to optionally include validation against an element based on prerequisites. So, in this instance, we need to verify the dimensions of an image based on the placement requested:
Our conditional request
Here, it’s actually quite readable what’s going on. We’re passing a sometimes
key to the validator and parsing that requirement to closure, in this instance we're saying, on the request parameter of image
, apply the dimensions
ratio specified if the placement
parameter is of a certain string.
And there you have it, a simple and fluent way of conditionally adding requests to your validators.
Originally published at https://lukecurtis.me.