Validation

Introduction

Laravel provides several different approaches to validate your application's incoming data. By default, Laravel's base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP request with a variety of powerful validation rules.

Validation Quickstart

To learn about Laravel's powerful validation features, let's look at a complete example of validating a form and displaying the error messages back to the user.

Defining The Routes

First, let's assume we have the following routes defined in our routes/web.php file:

  1. Route::get('post/create', '[email protected]');
  2. Route::post('post', '[email protected]');

Of course, the GET route will display a form for the user to create a new blog post, while the POST route will store the new blog post in the database.

Creating The Controller

Next, let's take a look at a simple controller that handles these routes. We'll leave the store method empty for now:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use App\Http\Controllers\Controller;
  5. class PostController extends Controller
  6. {
  7. /**
  8. * Show the form to create a new blog post.
  9. *
  10. * @return Response
  11. */
  12. public function create()
  13. {
  14. return view('post.create');
  15. }
  16. /**
  17. * Store a new blog post.
  18. *
  19. * @param Request $request
  20. * @return Response
  21. */
  22. public function store(Request $request)
  23. {
  24. // Validate and store the blog post...
  25. }
  26. }

Writing The Validation Logic

Now we are ready to fill in our store method with the logic to validate the new blog post. If you examine your application's base controller (App\Http\Controllers\Controller) class, you will see that the class uses a ValidatesRequests trait. This trait provides a convenient validate method to all of your controllers.

The validate method accepts an incoming HTTP request and a set of validation rules. If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user. In the case of a traditional HTTP request, a redirect response will be generated, while a JSON response will be sent for AJAX requests.

To get a better understanding of the validate method, let's jump back into the store method:

  1. /**
  2. * Store a new blog post.
  3. *
  4. * @param Request $request
  5. * @return Response
  6. */
  7. public function store(Request $request)
  8. {
  9. $this->validate($request, [
  10. 'title' => 'required|unique:posts|max:255',
  11. 'body' => 'required',
  12. ]);
  13. // The blog post is valid, store in database...
  14. }

As you can see, we simply pass the incoming HTTP request and desired validation rules into the validate method. Again, if the validation fails, the proper response will automatically be generated. If the validation passes, our controller will continue executing normally.

Stopping On First Validation Failure

Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute:

  1. $this->validate($request, [
  2. 'title' => 'bail|required|unique:posts|max:255',
  3. 'body' => 'required',
  4. ]);

In this example, if the required rule on the title attribute fails, the unique rule will not be checked. Rules will be validated in the order they are assigned.

A Note On Nested Attributes

If your HTTP request contains "nested" parameters, you may specify them in your validation rules using "dot" syntax:

  1. $this->validate($request, [
  2. 'title' => 'required|unique:posts|max:255',
  3. 'author.name' => 'required',
  4. 'author.description' => 'required',
  5. ]);

Displaying The Validation Errors

So, what if the incoming request parameters do not pass the given validation rules? As mentioned previously, Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors will automatically be flashed to the session.

Again, notice that we did not have to explicitly bind the error messages to the view in our GET route. This is because Laravel will check for errors in the session data, and automatically bind them to the view if they are available. The $errors variable will be an instance of Illuminate\Support\MessageBag. For more information on working with this object, check out its documentation.

{tip} The $errors variable is bound to the view by the Illuminate\View\Middleware\ShareErrorsFromSession middleware, which is provided by the web middleware group. When this middleware is applied an $errors variable will always be available in your views, allowing you to conveniently assume the $errors variable is always defined and can be safely used.

So, in our example, the user will be redirected to our controller's create method when validation fails, allowing us to display the error messages in the view:

  1. <!-- /resources/views/post/create.blade.php -->
  2. <h1>Create Post</h1>
  3. @if (count($errors) > 0)
  4. <div class="alert alert-danger">
  5. <ul>
  6. @foreach ($errors->all() as $error)
  7. <li>{{ $error }}</li>
  8. @endforeach
  9. </ul>
  10. </div>
  11. @endif
  12. <!-- Create Post Form -->

Customizing The Flashed Error Format

If you wish to customize the format of the validation errors that are flashed to the session when validation fails, override the formatValidationErrors on your base controller. Don't forget to import the Illuminate\Contracts\Validation\Validator class at the top of the file:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Foundation\Bus\DispatchesJobs;
  4. use Illuminate\Contracts\Validation\Validator;
  5. use Illuminate\Routing\Controller as BaseController;
  6. use Illuminate\Foundation\Validation\ValidatesRequests;
  7. abstract class Controller extends BaseController
  8. {
  9. use DispatchesJobs, ValidatesRequests;
  10. /**
  11. * {@inheritdoc}
  12. */
  13. protected function formatValidationErrors(Validator $validator)
  14. {
  15. return $validator->errors()->all();
  16. }
  17. }

AJAX Requests & Validation

In this example, we used a traditional form to send data to the application. However, many applications use AJAX requests. When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

Form Request Validation

Creating Form Requests

For more complex validation scenarios, you may wish to create a "form request". Form requests are custom request classes that contain validation logic. To create a form request class, use the make:request Artisan CLI command:

  1. php artisan make:request StoreBlogPost

The generated class will be placed in the app/Http/Requests directory. If this directory does not exist, it will be created when you run the make:request command. Let's add a few validation rules to the rules method:

  1. /**
  2. * Get the validation rules that apply to the request.
  3. *
  4. * @return array
  5. */
  6. public function rules()
  7. {
  8. return [
  9. 'title' => 'required|unique:posts|max:255',
  10. 'body' => 'required',
  11. ];
  12. }

So, how are the validation rules evaluated? All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic:

  1. /**
  2. * Store the incoming blog post.
  3. *
  4. * @param StoreBlogPost $request
  5. * @return Response
  6. */
  7. public function store(StoreBlogPost $request)
  8. {
  9. // The incoming request is valid...
  10. }

If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.

Authorizing Form Requests

The form request class also contains an authorize method. Within this method, you may check if the authenticated user actually has the authority to update a given resource. For example, you may determine if a user actually owns a blog comment they are attempting to update:

  1. /**
  2. * Determine if the user is authorized to make this request.
  3. *
  4. * @return bool
  5. */
  6. public function authorize()
  7. {
  8. $comment = Comment::find($this->route('comment'));
  9. return $comment && $this->user()->can('update', $comment);
  10. }

Since all form requests extend the base Laravel request class, we may use the user method to access the currently authenticated user. Also note the call to the route method in the example above. This method grants you access to the URI parameters defined on the route being called, such as the {comment} parameter in the example below:

  1. Route::post('comment/{comment}');

If the authorize method returns false, a HTTP response with a 403 status code will automatically be returned and your controller method will not execute.

If you plan to have authorization logic in another part of your application, simply return true from the authorize method:

  1. /**
  2. * Determine if the user is authorized to make this request.
  3. *
  4. * @return bool
  5. */
  6. public function authorize()
  7. {
  8. return true;
  9. }

Customizing The Error Format

If you wish to customize the format of the validation errors that are flashed to the session when validation fails, override the formatErrors on your base request (App\Http\Requests\Request). Don't forget to import the Illuminate\Contracts\Validation\Validator class at the top of the file:

  1. /**
  2. * {@inheritdoc}
  3. */
  4. protected function formatErrors(Validator $validator)
  5. {
  6. return $validator->errors()->all();
  7. }

Customizing The Error Messages

You may customize the error messages used by the form request by overriding the messages method. This method should return an array of attribute / rule pairs and their corresponding error messages:

  1. /**
  2. * Get the error messages for the defined validation rules.
  3. *
  4. * @return array
  5. */
  6. public function messages()
  7. {
  8. return [
  9. 'title.required' => 'A title is required',
  10. 'body.required' => 'A message is required',
  11. ];
  12. }

Manually Creating Validators

If you do not want to use the ValidatesRequests trait's validate method, you may create a validator instance manually using the Validator facade. The make method on the facade generates a new validator instance:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Validator;
  4. use Illuminate\Http\Request;
  5. use App\Http\Controllers\Controller;
  6. class PostController extends Controller
  7. {
  8. /**
  9. * Store a new blog post.
  10. *
  11. * @param Request $request
  12. * @return Response
  13. */
  14. public function store(Request $request)
  15. {
  16. $validator = Validator::make($request->all(), [
  17. 'title' => 'required|unique:posts|max:255',
  18. 'body' => 'required',
  19. ]);
  20. if ($validator->fails()) {
  21. return redirect('post/create')
  22. ->withErrors($validator)
  23. ->withInput();
  24. }
  25. // Store the blog post...
  26. }
  27. }

The first argument passed to the make method is the data under validation. The second argument is the validation rules that should be applied to the data.

After checking if the request validation failed, you may use the withErrors method to flash the error messages to the session. When using this method, the $errors variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user. The withErrors method accepts a validator, a MessageBag, or a PHP array.

Automatic Redirection

If you would like to create a validator instance manually but still take advantage of the automatic redirection offered by the ValidatesRequest trait, you may call the validate method on an existing validator instance. If validation fails, the user will automatically be redirected or, in the case of an AJAX request, a JSON response will be returned:

  1. Validator::make($request->all(), [
  2. 'title' => 'required|unique:posts|max:255',
  3. 'body' => 'required',
  4. ])->validate();

Named Error Bags

If you have multiple forms on a single page, you may wish to name the MessageBag of errors, allowing you to retrieve the error messages for a specific form. Simply pass a name as the second argument to withErrors:

  1. return redirect('register')
  2. ->withErrors($validator, 'login');

You may then access the named MessageBag instance from the $errors variable:

  1. {{ $errors->login->first('email') }}

After Validation Hook

The validator also allows you to attach callbacks to be run after validation is completed. This allows you to easily perform further validation and even add more error messages to the message collection. To get started, use the after method on a validator instance:

  1. $validator = Validator::make(...);
  2. $validator->after(function ($validator) {
  3. if ($this->somethingElseIsInvalid()) {
  4. $validator->errors()->add('field', 'Something is wrong with this field!');
  5. }
  6. });
  7. if ($validator->fails()) {
  8. //
  9. }

Working With Error Messages

After calling the errors method on a Validator instance, you will receive an Illuminate\Support\MessageBag instance, which has a variety of convenient methods for working with error messages. The $errors variable that is automatically made available to all views is also an instance of the MessageBag class.

Retrieving The First Error Message For A Field

To retrieve the first error message for a given field, use the first method:

  1. $errors = $validator->errors();
  2. echo $errors->first('email');

Retrieving All Error Messages For A Field

If you need to retrieve an array of all the messages for a given field, use the get method:

  1. foreach ($errors->get('email') as $message) {
  2. //
  3. }

If you are validating an array form field, you may retrieve all of the messages for each of the array elements using the * character:

  1. foreach ($errors->get('attachments.*') as $message) {
  2. //
  3. }

Retrieving All Error Messages For All Fields

To retrieve an array of all messages for all fields, use the all method:

  1. foreach ($errors->all() as $message) {
  2. //
  3. }

Determining If Messages Exist For A Field

The has method may be used to determine if any error messages exist for a given field:

  1. if ($errors->has('email')) {
  2. //
  3. }

Custom Error Messages

If needed, you may use custom error messages for validation instead of the defaults. There are several ways to specify custom messages. First, you may pass the custom messages as the third argument to the Validator::make method:

  1. $messages = [
  2. 'required' => 'The :attribute field is required.',
  3. ];
  4. $validator = Validator::make($input, $rules, $messages);

In this example, the :attribute place-holder will be replaced by the actual name of the field under validation. You may also utilize other place-holders in validation messages. For example:

  1. $messages = [
  2. 'same' => 'The :attribute and :other must match.',
  3. 'size' => 'The :attribute must be exactly :size.',
  4. 'between' => 'The :attribute must be between :min - :max.',
  5. 'in' => 'The :attribute must be one of the following types: :values',
  6. ];

Specifying A Custom Message For A Given Attribute

Sometimes you may wish to specify a custom error messages only for a specific field. You may do so using "dot" notation. Specify the attribute's name first, followed by the rule:

  1. $messages = [
  2. 'email.required' => 'We need to know your e-mail address!',
  3. ];

Specifying Custom Messages In Language Files

In most cases, you will probably specify your custom messages in a language file instead of passing them directly to the Validator. To do so, add your messages to custom array in the resources/lang/xx/validation.php language file.

  1. 'custom' => [
  2. 'email' => [
  3. 'required' => 'We need to know your e-mail address!',
  4. ],
  5. ],

Specifying Custom Attributes In Language Files

If you would like the :attribute portion of your validation message to be replaced with a custom attribute name, you may specify the custom name in the attributes array of your resources/lang/xx/validation.php language file:

  1. 'attributes' => [
  2. 'email' => 'email address',
  3. ],

Available Validation Rules

Below is a list of all available validation rules and their function:

AcceptedActive URLAfter (Date)AlphaAlpha DashAlpha NumericArrayBefore (Date)BetweenBooleanConfirmedDateDate FormatDifferentDigitsDigits BetweenDimensions (Image Files)DistinctE-MailExists (Database)FileFilledImage (File)InIn ArrayIntegerIP AddressJSONMaxMIME TypesMIME Type By File ExtensionMinNullableNot InNumericPresentRegular ExpressionRequiredRequired IfRequired UnlessRequired WithRequired With AllRequired WithoutRequired Without AllSameSizeStringTimezoneUnique (Database)URL

accepted

The field under validation must be yes, on, 1, or true. This is useful for validating "Terms of Service" acceptance.

active_url

The field under validation must have a valid A or AAAA record according to the dns_get_record PHP function.

after:date

The field under validation must be a value after a given date. The dates will be passed into the strtotime PHP function:

  1. 'start_date' => 'required|date|after:tomorrow'

Instead of passing a date string to be evaluated by strtotime, you may specify another field to compare against the date:

  1. 'finish_date' => 'required|date|after:start_date'

alpha

The field under validation must be entirely alphabetic characters.

alpha_dash

The field under validation may have alpha-numeric characters, as well as dashes and underscores.

alpha_num

The field under validation must be entirely alpha-numeric characters.

array

The field under validation must be a PHP array.

before:date

The field under validation must be a value preceding the given date. The dates will be passed into the PHP strtotime function.

between:min,max

The field under validation must have a size between the given min and max. Strings, numerics, and files are evaluated in the same fashion as the size rule.

boolean

The field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1", and "0".

confirmed

The field under validation must have a matching field of foo_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input.

date

The field under validation must be a valid date according to the strtotime PHP function.

date_format:format

The field under validation must match the given format. You should use either date or date_format when validating a field, not both.

different:field

The field under validation must have a different value than field.

digits:value

The field under validation must be numeric and must have an exact length of value.

digits_between:min,max

The field under validation must have a length between the given min and max.

dimensions

The file under validation must be an image meeting the dimension constraints as specified by the rule's parameters:

  1. 'avatar' => 'dimensions:min_width=100,min_height=200'

Available constraints are: min_width, max_width, min_height, max_height, width, height, ratio.

A ratio constraint should be represented as width divided by height. This can be specified either by a statement like 3/2 or a float like 1.5:

  1. 'avatar' => 'dimensions:ratio=3/2'

distinct

When working with arrays, the field under validation must not have any duplicate values.

  1. 'foo.*.id' => 'distinct'

email

The field under validation must be formatted as an e-mail address.

exists:table,column

The field under validation must exist on a given database table.

Basic Usage Of Exists Rule

  1. 'state' => 'exists:states'

Specifying A Custom Column Name

  1. 'state' => 'exists:states,abbreviation'

Occasionally, you may need to specify a specific database connection to be used for the exists query. You can accomplish this by prepending the connection name to the table name using "dot" syntax:

  1. 'email' => 'exists:connection.staff,email'

If you would like to customize the query executed by the validation rule, you may use the Rule class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the | character to delimit them:

  1. use Illuminate\Validation\Rule;
  2. Validator::make($data, [
  3. 'email' => [
  4. 'required',
  5. Rule::exists('staff')->where(function ($query) {
  6. $query->where('account_id', 1);
  7. }),
  8. ],
  9. ]);

file

The field under validation must be a successfully uploaded file.

filled

The field under validation must not be empty when it is present.

image

The file under validation must be an image (jpeg, png, bmp, gif, or svg)

in:foo,bar,…

The field under validation must be included in the given list of values.

in_array:anotherfield

The field under validation must exist in anotherfield's values.

integer

The field under validation must be an integer.

ip

The field under validation must be an IP address.

json

The field under validation must be a valid JSON string.

max:value

The field under validation must be less than or equal to a maximum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

mimetypes:text/plain,…

The file under validation must match one of the given MIME types:

  1. 'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime'

To determine the MIME type of the uploaded file, the file's contents will be read and the framework will attempt to guess the MIME type, which may be different from the client provided MIME type.

mimes:foo,bar,…

The file under validation must have a MIME type corresponding to one of the listed extensions.

Basic Usage Of MIME Rule

  1. 'photo' => 'mimes:jpeg,bmp,png'

Even though you only need to specify the extensions, this rule actually validates against the MIME type of the file by reading the file's contents and guessing its MIME type.

A full listing of MIME types and their corresponding extensions may be found at the following location: https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

min:value

The field under validation must have a minimum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

nullable

The field under validation may be null. This is particularly useful when validating primitive such as strings and integers that can contain null values.

not_in:foo,bar,…

The field under validation must not be included in the given list of values.

numeric

The field under validation must be numeric.

present

The field under validation must be present in the input data but can be empty.

regex:pattern

The field under validation must match the given regular expression.

Note: When using the regex pattern, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

required

The field under validation must be present in the input data and not empty. A field is considered "empty" if one of the following conditions are true:

  • The value is null.
  • The value is an empty string.
  • The value is an empty array or empty Countable object.
  • The value is an uploaded file with no path.

required_if:anotherfield,value,…

The field under validation must be present and not empty if the anotherfield field is equal to any value.

required_unless:anotherfield,value,…

The field under validation must be present and not empty unless the anotherfield field is equal to any value.

required_with:foo,bar,…

The field under validation must be present and not empty only if any of the other specified fields are present.

required_with_all:foo,bar,…

The field under validation must be present and not empty only if all of the other specified fields are present.

required_without:foo,bar,…

The field under validation must be present and not empty only when any of the other specified fields are not present.

required_without_all:foo,bar,…

The field under validation must be present and not empty only when all of the other specified fields are not present.

same:field

The given field must match the field under validation.

size:value

The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value. For an array, size corresponds to the count of the array. For files, size corresponds to the file size in kilobytes.

string

The field under validation must be a string. If you would like to allow the field to also be null, you should assign the nullable rule to the field.

timezone

The field under validation must be a valid timezone identifier according to the timezone_identifiers_list PHP function.

unique:table,column,except,idColumn

The field under validation must be unique in a given database table. If the column option is not specified, the field name will be used.

Specifying A Custom Column Name:

  1. 'email' => 'unique:users,email_address'

Custom Database Connection

Occasionally, you may need to set a custom connection for database queries made by the Validator. As seen above, setting unique:users as a validation rule will use the default database connection to query the database. To override this, specify the connection and the table name using "dot" syntax:

  1. 'email' => 'unique:connection.users,email_address'

Forcing A Unique Rule To Ignore A Given ID:

Sometimes, you may wish to ignore a given ID during the unique check. For example, consider an "update profile" screen that includes the user's name, e-mail address, and location. Of course, you will want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address.

To instruct the validator to ignore the user's ID, we'll use the Rule class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the | character to delimit the rules:

  1. use Illuminate\Validation\Rule;
  2. Validator::make($data, [
  3. 'email' => [
  4. 'required',
  5. Rule::unique('users')->ignore($user->id),
  6. ],
  7. ]);

If your table uses a primary key column name other than id, you may specify the name of the column when calling the ignore method:

  1. 'email' => Rule::unique('users')->ignore($user->id, 'user_id')

Adding Additional Where Clauses:

You may also specify additional query constraints by customizing the query using the where method. For example, let's add a constraint that verifies the account_id is 1:

  1. 'email' => Rule::unique('users')->where(function ($query) {
  2. $query->where('account_id', 1);
  3. })

url

The field under validation must be a valid URL.

Conditionally Adding Rules

Validating When Present

In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list:

  1. $v = Validator::make($data, [
  2. 'email' => 'sometimes|required|email',
  3. ]);

In the example above, the email field will only be validated if it is present in the $data array.

Complex Conditional Validation

Sometimes you may wish to add validation rules based on more complex conditional logic. For example, you may wish to require a given field only if another field has a greater value than 100. Or, you may need two fields to have a given value only when another field is present. Adding these validation rules doesn't have to be a pain. First, create a Validator instance with your static rules that never change:

  1. $v = Validator::make($data, [
  2. 'email' => 'required|email',
  3. 'games' => 'required|numeric',
  4. ]);

Let's assume our web application is for game collectors. If a game collector registers with our application and they own more than 100 games, we want them to explain why they own so many games. For example, perhaps they run a game resale shop, or maybe they just enjoy collecting. To conditionally add this requirement, we can use the sometimes method on the Validator instance.

  1. $v->sometimes('reason', 'required|max:500', function ($input) {
  2. return $input->games >= 100;
  3. });

The first argument passed to the sometimes method is the name of the field we are conditionally validating. The second argument is the rules we want to add. If the Closure passed as the third argument returns true, the rules will be added. This method makes it a breeze to build complex conditional validations. You may even add conditional validations for several fields at once:

  1. $v->sometimes(['reason', 'cost'], 'required', function ($input) {
  2. return $input->games >= 100;
  3. });

{tip} The $input parameter passed to your Closure will be an instance of Illuminate\Support\Fluent and may be used to access your input and files.

Validating Arrays

Validating array based form input fields doesn't have to be a pain. For example, to validate that each e-mail in a given array input field is unique, you may do the following:

  1. $validator = Validator::make($request->all(), [
  2. 'person.*.email' => 'email|unique:users',
  3. 'person.*.first_name' => 'required_with:person.*.last_name',
  4. ]);

Likewise, you may use the * character when specifying your validation messages in your language files, making it a breeze to use a single validation message for array based fields:

  1. 'custom' => [
  2. 'person.*.email' => [
  3. 'unique' => 'Each person must have a unique e-mail address',
  4. ]
  5. ],

Custom Validation Rules

Laravel provides a variety of helpful validation rules; however, you may wish to specify some of your own. One method of registering custom validation rules is using the extend method on the Validator facade. Let's use this method within a service provider to register a custom validation rule:

  1. <?php
  2. namespace App\Providers;
  3. use Illuminate\Support\ServiceProvider;
  4. use Illuminate\Support\Facades\Validator;
  5. class AppServiceProvider extends ServiceProvider
  6. {
  7. /**
  8. * Bootstrap any application services.
  9. *
  10. * @return void
  11. */
  12. public function boot()
  13. {
  14. Validator::extend('foo', function ($attribute, $value, $parameters, $validator) {
  15. return $value == 'foo';
  16. });
  17. }
  18. /**
  19. * Register the service provider.
  20. *
  21. * @return void
  22. */
  23. public function register()
  24. {
  25. //
  26. }
  27. }

The custom validator Closure receives four arguments: the name of the $attribute being validated, the $value of the attribute, an array of $parameters passed to the rule, and the Validator instance.

You may also pass a class and method to the extend method instead of a Closure:

  1. Validator::extend('foo', '[email protected]');

Defining The Error Message

You will also need to define an error message for your custom rule. You can do so either using an inline custom message array or by adding an entry in the validation language file. This message should be placed in the first level of the array, not within the custom array, which is only for attribute-specific error messages:

  1. "foo" => "Your input was invalid!",
  2. "accepted" => "The :attribute must be accepted.",
  3. // The rest of the validation error messages...

When creating a custom validation rule, you may sometimes need to define custom place-holder replacements for error messages. You may do so by creating a custom Validator as described above then making a call to the replacer method on the Validator facade. You may do this within the boot method of a service provider:

  1. /**
  2. * Bootstrap any application services.
  3. *
  4. * @return void
  5. */
  6. public function boot()
  7. {
  8. Validator::extend(...);
  9. Validator::replacer('foo', function ($message, $attribute, $rule, $parameters) {
  10. return str_replace(...);
  11. });
  12. }

Implicit Extensions

By default, when an attribute being validated is not present or contains an empty value as defined by the required rule, normal validation rules, including custom extensions, are not run. For example, the unique rule will not be run against a null value:

  1. $rules = ['name' => 'unique'];
  2. $input = ['name' => null];
  3. Validator::make($input, $rules)->passes(); // true

For a rule to run even when an attribute is empty, the rule must imply that the attribute is required. To create such an "implicit" extension, use the Validator::extendImplicit() method:

  1. Validator::extendImplicit('foo', function ($attribute, $value, $parameters, $validator) {
  2. return $value == 'foo';
  3. });

{note} An "implicit" extension only implies that the attribute is required. Whether it actually invalidates a missing or empty attribute is up to you.