A common mistake with Laravel and form validation

First of all, thanks for visiting my blog (again). It has been a while since my last post since I’m kinda busy with all kinds of things at the moment.

Today I’m not going to talk about WordPress, since that it not the only thing I’d like to share knowledge about. Today is about Laravel, a well-written PHP framework “Made for artisans”. Since Laravel 5.0 it offers a extendable request class, which allows you to handle form validation before your controller method even gets called. One of the nice things about using form requests is that it really helps keeping your controllers clean, like how they use to be.

In the examples below I’m going to show how you’re supposed to handle validation in Laravel 5.0+. But please keep in mind that it’s not mandatory to use this way, when you’re just building a small application you could always handle validation in your controller.

Creating a request

Since Laravel offers a really nice command line tool, why not use it for creating a request? For example, I’m creating a request for creating an article. My form will contain a title field, a textarea and a (post)-date field.

php artisan make:request CreateArticleRequest

When the command is executed successfully, you’ll get something like “Request created successfully”.

The request explained

When you open up the generated request file, you’ll find some default code that might confuse you. By default, it contains 2 methods: authorize, and rules. The authorize method handles the authentication of the request. If you would like the user to be authenticated before the form may be executed, you should place that logic right here.

The “rules” method is going to contain all of our validation rules.

Creating validation rules

Setting up the rules is pretty simple, too. If you’ve ever made validation rules yourself in Laraval you could almost skip this step. Creating validation rules is exactly the same.

Let’s say that all of our fields are required, the textarea should contains at leasts 5 characters, and the date should be a date-formatted string. This would create something like:

 * Get the validation rules that apply to the request.
 * @return array
public function rules()
 return [
  'title'   => 'required',
  'message' => 'required|min:5',
  'date'    => 'required|date',

If one of the above rules fail, your controller method will not even be executed. The page will redirect you back to the page your visitor came from. The validation messages will be stored in a so-called “ErrorBag”, which you can display using the variable $errors in your templates.

If you’d like to know more about using form requests, I’d really recommend watching the Laracast about form validation. Also, if you need more than just min-characters, date validation or required. You should check out this page. It lists all of the available validation methods.