Search

Laravel Application Helper Function: validator

November 20, 2016 —John Koster

validator(array $data = [], array $rules = [], array $messages = [], array $customAttributes = [])

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 following examples are equivalent; all the examples will make use of the request helper function.

1<?php
2 
3use Illuminate\Support\Facades\Validator;
4 
5// Using the Validator facade.
6$validator = Validator::make(request()->all(), [
7 'title' => 'required|unique:posts|max:255',
8 'body' => 'required'
9]);
10 
11// Using the validator helper function.
12$anotherValidator = validator()->make(request()->all(), [
13 'title' => 'required|unique:posts|max:255',
14 'body' => 'required'
15]);

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<?php
2 
3$validator = validator(request()->all, [
4 'title' => 'required|unique:posts|max:255',
5 'body' => 'required'
6]);

Some absolutely amazing
people

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.