Making sure you validate any input data from the user is crucial for security and ensuring your app stays in a valid state. Validating data is easy peasy lemon squeezy with Laravel’s validation rules in combination with form request objects.
Another thing Laravel does, is make it super easy to access request input data. A form request object extends Laravel’s request object, so accessing a title input is as easy as
$request->title, but there lays the potential issue. It can be too easy, let’s take a look at why.
Creating Models from Request Data
In your controller, you’ve probably done something like this to create a pretty simple model:
or another option might be something like:
Both a perfectly valid options and I’ve been doing this myself in my projects. However, recently I was thinking it is very possible to access input from the form that hasn’t been validated. Looking at this, how do I know those are validated inputs?
When I’m in my controller, I don’t know if the form has validated the
content input…and that scares me - sure, I’m a big kid and should trust that I did validate the data, but with such an important piece of the puzzle I don’t like to take any risks.
Enforcing Valid Data Access
Let’s wrap ourselves up in a security blanket so we can sleep easy. In a form request object we set our rules as per normal:
and then we add a new method to our request object to keep ourselves in check:
Now in our controller we know that our input has been validated by our rules and is of a type that is suitable for our application.
😌 that makes me feel better.
- This could of course be extended to include other helpful methods such as
- This works great with flat arrays, but once you you are creating more complex rules such as:
things start to get a little hairy, but by then you’re probably doing other trickery anyway.
- Check out my fluent validation rule builder, if you are into that.
- I’ve created a Trait to wrap this up if you are interested in this functionality or want to contribute to make it more awesome. Visit the repo.
Looks like we are going to have this baked into the upcoming Laravel release 5.5 thanks to Joseph Silber. Very cool - looking forward to trying it!