Laravel: Custom Validation

Reading time ~1 minute

Laravel form validation is simple enough, but what if you want to extend the validation and do your own?

It's easy enough to do if you are doing everything in the routing, but that is going to get out of control really quickly. You can even abstract it another level into the controller, and even that becomes repetitive. If you have done any Googling, you have probably seen this tutorial by Jeffrey Way. This will get you about 90% of the way there. But what if you want a CUSTOM validation method? Continuing from where Jeffrey left off, lets say you have the following `$rules`.

public static $rules = [
	'title' => 'required',
	'body' => 'required|divisible_by_two'
Notice, the above should be the same as from the custom validation class in the aforementioned tutorial, save for one change. We have added `divisible_by_two`. This is making reference to a not yet created validation rule. Lets go ahead and add that now. I am going to start by adding a new constructor inside the Services\Validators\Post class. Remember we need to include `parent::__construct();` in order to keep the changes from the abstract validator class.

public function __construct() {
	\Validator::extend('divisible_by_two', 'Services\Validators\Post@divisible_by_two');
Note: In the above uses namespaces for the second parameter in `Validator::extend()`. This is key, since we are using namespaces, we need to remember them here.

Lastly we need to add our method that does the actual validation.

public function divisible_by_two($attribute, $value, $parameters) {
        return ($value % 2) === 0;
And that should be it! Your custom validator should now be in effect. Drink Responsibly!

Quick Laravel/Lumen install with Docker!

The default installer that comes with Laravel is great, but unfortunately that means you have to install dependencies of PHP and Laravel/...… Continue reading

PHP To Python

Published on February 24, 2016

Aftertouch in Logic Pro X and 2015 Macbook Pro

Published on February 24, 2016