April 14, 2018 —John Koster
The validator
helper function is a versatile helper function. If no arguments are supplied to the validator
function (all arguments are optional), the function will return a "Illuminate\Contracts\Validation\Factory" implementation instance (the default implementation will be an instance of "Illuminate\Validation\Factory").
Using the validator
function without arguments and gaining access to the instance methods is essentially the same as using the "Illuminate\Support\Facades\Validator" facade.
The signature of the validator
function is:
1 2function validator();3 4function validator(5 array $data = [],6 array $rules = [],7 array $messages = [],8 array $customAttributes []9);
The following examples are equivalent; all the examples will make use of the request
helper function.
1use Illuminate\Support\Facades\Validator; 2 3// Using the Validator facade. 4$validator = Validator::make(request()->all(), [ 5 'title' => 'required|unique:posts|max:255', 6 'body' => 'required' 7]); 8 9// Using the validator helper function.10$anotherValidator = validator()->make(request()->all(), [11 'title' => 'required|unique:posts|max:255',12 'body' => 'required'13]);
The second example above can be shortened even further. You can supply the arguments for the make
instance method directly to the validator
helper function. When you supply arguments to the validator
helper function it will call and return the value of the make
instance method:
1$validator = validator(request()->all, [2 'title' => 'required|unique:posts|max:255',3 'body' => 'required'4]);
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.