Custom validators in Laravel

I’m still going with the Laravel port. One thing I’ve found really interesting is custom validators. In Laravel models you can set field rules, such as…

public static $rules = array(
    'name'                => 'required|alpha_spaces|unique:jars',
    'ownerID'             => 'integer',
    'isBreedingJar'       => 'boolean',
    'capacity'            => 'integer|max:15',
    'comment'             => 'between:0,32|alpha_spaces',
);

{:lang=“php”}

In the vanilla PHP version I had to perform a check in updateSnail() - if the modified field was currentJarID, I had to find the number of snails inside a jar with that same ID and compare the jar’s capacity to the count of those snails. If capacity <= current snail count, the snail was not allowed to be placed into that jar.

With Laravel, I hacked together the same thing in the form of a new validation rule. This way I don’t have to explicitly perform this check whenever I move a snail myself - I just set the rule name in the rules array for the Snail model and it does the rest whenever it sees the snail’s currentJarID being modified.

I plan on changing this when I can see better ways of doing this. For now, setting it up like this seems to work:

1) Create app/validators.php

2) Extend Validator with your own rule

Validator::extend('limited_jar_space', function($attribute, $value, $parameters)
{
	$jarID = Input::get('currentJarID');

	$jarController = new JarController();
	$jar = $jarController->getJarDetails($jarID, 'capacity');
	
	$snailController = new SnailController();
	$snailCount = count($snailController->findSnailsInJar($jarID));

	if ($jar->capacity <= $snailCount) {
		return false;
	}
	return true;
});

{:lang=“php”}

3) Create a custom error message in lang/x/validation.php

"limited_jar_space"		=> "The jar is full!",

{:lang=“php”}

4) Add app/validators.php to start/global.php

require app_path().'/validators.php';

{:lang=“php”}

5) So now I can use the rule "limited_jar_space" for currentJarID in the snail model to make sure the jar a user is trying to move their snail to has enough space left.

public static $rules = array(
    'name'              	 => 'alpha_spaces|unique:snails',
    'ownerID'                => 'integer',
    'currentJarID'           => 'integer|limited_jar_space',
);

{:lang=“php”}

comments powered by Disqus