I review a fair number of Laravel projects each year, and it's common to see validation rules that are weaker than they could be. This is a big reason we wrote a whole book on the topic.
Today, I want to share one simple tip that is easy to implement and can avoid some fairly common unhandled exceptions in production.
If the form input is going to be saved to a database, you should always add a rule to validate the maximum length of the input.
For example, if the name
field in a form is going to be saved to a VARCHAR(255)
column, you should have a max:255
rule on that field.
There are variations on this for other column types, but the principle is the same.
If you don't enforce this rule, and someone overflows that maximum length, instead of a friendly validation error, they'll get a database exception and a very unhelpful HTTP 500
error.
Of course, there may be business reasons to set the maximum value even lower than the database schema's maximum, but you should always have a rule in place.
Here to help,
Joel
P.S. The Mastering Laravel Validation Rules book has dozens of practical tips like this, along with numerous code examples showing how to use validation rules to write more reliable Laravel apps.