in Laravel, Programming

Reduce Validation Bloat in Laravel Controllers

In Laravel or Lumen, I’ve often noticed that a significant portion of my controllers can be validation calls. To solve this, I moved validation rules to a config file. By doing so, you can often simplify validation to just a single line of code.

This allows you to go from this:

$this->validate($request, [
    'title' => 'required|unique:posts|max:255',
    'excerpt' => 'max:255',
    'body' => 'required',
    'category' => 'required',
    'tags' => 'array',
    'status' => 'required|in:draft,scheduled,published',
    'publish_at' => 'nullable|date',
]);

To just one line of code like this:

$this->validate($request, config('validation.post.create'));

How To Pull Validation From A Config File

Create /config/validation.php and add your rules:

<?php
return [ 
    'post' => [
        'create' => [
            'title' => 'required|unique:posts|max:255',
            'excerpt' => 'max:255',
            'body' => 'required',
            'category' => 'required',
            'tags' => 'array',
            'status' => 'required|in:draft,scheduled,published',
            'publish_at' => 'nullable|date',
        ]
    ]
];

Lumen: You’ll need to load the config file manually. Open /bootstrap/app.php and after the line $app->withEloquent(); add this: $app->configure('validation');.

Enjoy.

Wait, What about form request objects? They can be used to move validation bloat out of controllers too!

True, I’m a big fan of how form requests move validation and data transformation to a separate step before controller execution. However, I think you’ll find having all these different request objects (often just for the purpose of returning validation rules), can be overkill when you could just pull it from a config file. Not to mention, Lumen doesn’t support form requests, so this is a great alternative if you’re using Lumen.

Follow me on Twitter, or subscribe to Laravel/Programming for future posts.


Also published on Medium.