0

I'm adding custom validation rules to my Laravel 5.1 application, and I currently have it set up like this in AppServiceProvider:

    Validator::extend('word_count', 'App\CustomValidators@wordCount');
    Validator::extend('required_if_not', 'App\CustomValidators@requiredIfNot');
    Validator::extend('date_in_year', 'App\CustomValidators@dateInYear');

This works, but I'm wondering if there is a better method I should be using with 5.1 rather than calling the Validator facade.

For example, calling to a view no longer requires me to call View::request('template', $viewData) or View::make('template', $viewData), but instead I can call view('template', $viewData), which cuts down on the number of namespaces I need to 'use' for my class. I can do something similar with redirects as well.

What is the best/cleanest method in Laravel 5.1 for adding custom validation rules?

2
  • 1
    Lisa, somethings the shortest way is not the best/cleanest. When the project is getting large is good to keep things in order instead putting extra effort-time just to save some characters. Take a look to this way: stackoverflow.com/questions/28417977/… Commented Oct 14, 2015 at 20:49
  • This question is part of a refactoring session that I'm doing on my project. It's less to minimize the number of characters that are used and more to learn best practices for Laravel 5.1. This application was upgraded from Laravel 4.1, so there's a lot in there that's still following those practices. Commented Oct 14, 2015 at 20:53

1 Answer 1

1

Well, a probably solution here is to create a custom function (helper function as view()) to avoid the facade.

if (! function_exists('validator_ext')) {
    /**
     * Adding custom rules
     *
     * @param  string  $name
     * @param  array   $listener
     * @return \Illuminate\Validation\Factory
     */
    function validator_ext($name, $listener)
    {
        $validator = app('Illuminate\Validation\Factory');
        $validator->extend($name, $listener);
        return $validator;
    }
}

Now you are able to call it as:

validator_ext('word_count', 'App\CustomValidators@wordCount');

Another way without using a helper function is to instantiate the validator at boot method:

$validator = app('Illuminate\Validation\Factory');
$validator->extend('word_count', 'App\CustomValidators@wordCount');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, both of those solutions look interesting. I'll play around with them and see how they go!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.