502 | */
503 | public function attributes(): array
504 | {
505 | return [
506 | 'email' => 'email address',
507 | ];
508 | }
509 |
510 |
511 | ### Preparing Input For Validation
512 |
513 | If you need to prepare or sanitize any data from the request before you apply your validation rules, you may use the `prepareForValidation` method:
514 |
515 | use Illuminate\Support\Str;
516 |
517 | /**
518 | * Prepare the data for validation.
519 | */
520 | protected function prepareForValidation(): void
521 | {
522 | $this->merge([
523 | 'slug' => Str::slug($this->slug),
524 | ]);
525 | }
526 |
527 | Likewise, if you need to normalize any request data after validation is complete, you may use the `passedValidation` method:
528 |
529 | /**
530 | * Handle a passed validation attempt.
531 | */
532 | protected function passedValidation(): void
533 | {
534 | $this->replace(['name' => 'Taylor']);
535 | }
536 |
537 |
538 | ## Manually Creating Validators
539 |
540 | If you do not want to use the `validate` method on the request, you may create a validator instance manually using the `Validator` [facade](/docs/{{version}}/facades). The `make` method on the facade generates a new validator instance:
541 |
542 | all(), [
559 | 'title' => 'required|unique:posts|max:255',
560 | 'body' => 'required',
561 | ]);
562 |
563 | if ($validator->fails()) {
564 | return redirect('post/create')
565 | ->withErrors($validator)
566 | ->withInput();
567 | }
568 |
569 | // Retrieve the validated input...
570 | $validated = $validator->validated();
571 |
572 | // Retrieve a portion of the validated input...
573 | $validated = $validator->safe()->only(['name', 'email']);
574 | $validated = $validator->safe()->except(['name', 'email']);
575 |
576 | // Store the blog post...
577 |
578 | return redirect('/posts');
579 | }
580 | }
581 |
582 | The first argument passed to the `make` method is the data under validation. The second argument is an array of the validation rules that should be applied to the data.
583 |
584 | After determining whether 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`.
585 |
586 | #### Stopping On First Validation Failure
587 |
588 | The `stopOnFirstFailure` method will inform the validator that it should stop validating all attributes once a single validation failure has occurred:
589 |
590 | if ($validator->stopOnFirstFailure()->fails()) {
591 | // ...
592 | }
593 |
594 |
595 | ### Automatic Redirection
596 |
597 | If you would like to create a validator instance manually but still take advantage of the automatic redirection offered by the HTTP request's `validate` method, 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 XHR request, a [JSON response will be returned](#validation-error-response-format):
598 |
599 | Validator::make($request->all(), [
600 | 'title' => 'required|unique:posts|max:255',
601 | 'body' => 'required',
602 | ])->validate();
603 |
604 | You may use the `validateWithBag` method to store the error messages in a [named error bag](#named-error-bags) if validation fails:
605 |
606 | Validator::make($request->all(), [
607 | 'title' => 'required|unique:posts|max:255',
608 | 'body' => 'required',
609 | ])->validateWithBag('post');
610 |
611 |
612 | ### Named Error Bags
613 |
614 | If you have multiple forms on a single page, you may wish to name the `MessageBag` containing the validation errors, allowing you to retrieve the error messages for a specific form. To achieve this, pass a name as the second argument to `withErrors`:
615 |
616 | return redirect('register')->withErrors($validator, 'login');
617 |
618 | You may then access the named `MessageBag` instance from the `$errors` variable:
619 |
620 | ```blade
621 | {{ $errors->login->first('email') }}
622 | ```
623 |
624 |
625 | ### Customizing The Error Messages
626 |
627 | If needed, you may provide custom error messages that a validator instance should use instead of the default error messages provided by Laravel. There are several ways to specify custom messages. First, you may pass the custom messages as the third argument to the `Validator::make` method:
628 |
629 | $validator = Validator::make($input, $rules, $messages = [
630 | 'required' => 'The :attribute field is required.',
631 | ]);
632 |
633 | In this example, the `:attribute` placeholder will be replaced by the actual name of the field under validation. You may also utilize other placeholders in validation messages. For example:
634 |
635 | $messages = [
636 | 'same' => 'The :attribute and :other must match.',
637 | 'size' => 'The :attribute must be exactly :size.',
638 | 'between' => 'The :attribute value :input is not between :min - :max.',
639 | 'in' => 'The :attribute must be one of the following types: :values',
640 | ];
641 |
642 |
643 | #### Specifying A Custom Message For A Given Attribute
644 |
645 | Sometimes you may wish to specify a custom error message only for a specific attribute. You may do so using "dot" notation. Specify the attribute's name first, followed by the rule:
646 |
647 | $messages = [
648 | 'email.required' => 'We need to know your email address!',
649 | ];
650 |
651 |
652 | #### Specifying Custom Attribute Values
653 |
654 | Many of Laravel's built-in error messages include an `:attribute` placeholder that is replaced with the name of the field or attribute under validation. To customize the values used to replace these placeholders for specific fields, you may pass an array of custom attributes as the fourth argument to the `Validator::make` method:
655 |
656 | $validator = Validator::make($input, $rules, $messages, [
657 | 'email' => 'email address',
658 | ]);
659 |
660 |
661 | ### Performing Additional Validation
662 |
663 | Sometimes you need to perform additional validation after your initial validation is complete. You can accomplish this using the validator's `after` method. The `after` method accepts a closure or an array of callables which will be invoked after validation is complete. The given callables will receive an `Illuminate\Validation\Validator` instance, allowing you to raise additional error messages if necessary:
664 |
665 | use Illuminate\Support\Facades\Validator;
666 |
667 | $validator = Validator::make(/* ... */);
668 |
669 | $validator->after(function ($validator) {
670 | if ($this->somethingElseIsInvalid()) {
671 | $validator->errors()->add(
672 | 'field', 'Something is wrong with this field!'
673 | );
674 | }
675 | });
676 |
677 | if ($validator->fails()) {
678 | // ...
679 | }
680 |
681 | As noted, the `after` method also accepts an array of callables, which is particularly convenient if your "after validation" logic is encapsulated in invokable classes, which will receive an `Illuminate\Validation\Validator` instance via their `__invoke` method:
682 |
683 | ```php
684 | use App\Validation\ValidateShippingTime;
685 | use App\Validation\ValidateUserStatus;
686 |
687 | $validator->after([
688 | new ValidateUserStatus,
689 | new ValidateShippingTime,
690 | function ($validator) {
691 | // ...
692 | },
693 | ]);
694 | ```
695 |
696 |
697 | ## Working With Validated Input
698 |
699 | After validating incoming request data using a form request or a manually created validator instance, you may wish to retrieve the incoming request data that actually underwent validation. This can be accomplished in several ways. First, you may call the `validated` method on a form request or validator instance. This method returns an array of the data that was validated:
700 |
701 | $validated = $request->validated();
702 |
703 | $validated = $validator->validated();
704 |
705 | Alternatively, you may call the `safe` method on a form request or validator instance. This method returns an instance of `Illuminate\Support\ValidatedInput`. This object exposes `only`, `except`, and `all` methods to retrieve a subset of the validated data or the entire array of validated data:
706 |
707 | $validated = $request->safe()->only(['name', 'email']);
708 |
709 | $validated = $request->safe()->except(['name', 'email']);
710 |
711 | $validated = $request->safe()->all();
712 |
713 | In addition, the `Illuminate\Support\ValidatedInput` instance may be iterated over and accessed like an array:
714 |
715 | // Validated data may be iterated...
716 | foreach ($request->safe() as $key => $value) {
717 | // ...
718 | }
719 |
720 | // Validated data may be accessed as an array...
721 | $validated = $request->safe();
722 |
723 | $email = $validated['email'];
724 |
725 | If you would like to add additional fields to the validated data, you may call the `merge` method:
726 |
727 | $validated = $request->safe()->merge(['name' => 'Taylor Otwell']);
728 |
729 | If you would like to retrieve the validated data as a [collection](/docs/{{version}}/collections) instance, you may call the `collect` method:
730 |
731 | $collection = $request->safe()->collect();
732 |
733 |
734 | ## Working With Error Messages
735 |
736 | 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.
737 |
738 |
739 | #### Retrieving The First Error Message For A Field
740 |
741 | To retrieve the first error message for a given field, use the `first` method:
742 |
743 | $errors = $validator->errors();
744 |
745 | echo $errors->first('email');
746 |
747 |
748 | #### Retrieving All Error Messages For A Field
749 |
750 | If you need to retrieve an array of all the messages for a given field, use the `get` method:
751 |
752 | foreach ($errors->get('email') as $message) {
753 | // ...
754 | }
755 |
756 | If you are validating an array form field, you may retrieve all of the messages for each of the array elements using the `*` character:
757 |
758 | foreach ($errors->get('attachments.*') as $message) {
759 | // ...
760 | }
761 |
762 |
763 | #### Retrieving All Error Messages For All Fields
764 |
765 | To retrieve an array of all messages for all fields, use the `all` method:
766 |
767 | foreach ($errors->all() as $message) {
768 | // ...
769 | }
770 |
771 |
772 | #### Determining If Messages Exist For A Field
773 |
774 | The `has` method may be used to determine if any error messages exist for a given field:
775 |
776 | if ($errors->has('email')) {
777 | // ...
778 | }
779 |
780 |
781 | ### Specifying Custom Messages In Language Files
782 |
783 | Laravel's built-in validation rules each have an error message that is located in your application's `lang/en/validation.php` file. If your application does not have a `lang` directory, you may instruct Laravel to create it using the `lang:publish` Artisan command.
784 |
785 | Within the `lang/en/validation.php` file, you will find a translation entry for each validation rule. You are free to change or modify these messages based on the needs of your application.
786 |
787 | In addition, you may copy this file to another language directory to translate the messages for your application's language. To learn more about Laravel localization, check out the complete [localization documentation](/docs/{{version}}/localization).
788 |
789 | > **Warning**
790 | > By default, the Laravel application skeleton does not include the `lang` directory. If you would like to customize Laravel's language files, you may publish them via the `lang:publish` Artisan command.
791 |
792 |
793 | #### Custom Messages For Specific Attributes
794 |
795 | You may customize the error messages used for specified attribute and rule combinations within your application's validation language files. To do so, add your message customizations to the `custom` array of your application's `lang/xx/validation.php` language file:
796 |
797 | 'custom' => [
798 | 'email' => [
799 | 'required' => 'We need to know your email address!',
800 | 'max' => 'Your email address is too long!'
801 | ],
802 | ],
803 |
804 |
805 | ### Specifying Attributes In Language Files
806 |
807 | Many of Laravel's built-in error messages include an `:attribute` placeholder that is replaced with the name of the field or attribute under validation. If you would like the `:attribute` portion of your validation message to be replaced with a custom value, you may specify the custom attribute name in the `attributes` array of your `lang/xx/validation.php` language file:
808 |
809 | 'attributes' => [
810 | 'email' => 'email address',
811 | ],
812 |
813 | > **Warning**
814 | > By default, the Laravel application skeleton does not include the `lang` directory. If you would like to customize Laravel's language files, you may publish them via the `lang:publish` Artisan command.
815 |
816 |
817 | ### Specifying Values In Language Files
818 |
819 | Some of Laravel's built-in validation rule error messages contain a `:value` placeholder that is replaced with the current value of the request attribute. However, you may occasionally need the `:value` portion of your validation message to be replaced with a custom representation of the value. For example, consider the following rule that specifies that a credit card number is required if the `payment_type` has a value of `cc`:
820 |
821 | Validator::make($request->all(), [
822 | 'credit_card_number' => 'required_if:payment_type,cc'
823 | ]);
824 |
825 | If this validation rule fails, it will produce the following error message:
826 |
827 | ```none
828 | The credit card number field is required when payment type is cc.
829 | ```
830 |
831 | Instead of displaying `cc` as the payment type value, you may specify a more user-friendly value representation in your `lang/xx/validation.php` language file by defining a `values` array:
832 |
833 | 'values' => [
834 | 'payment_type' => [
835 | 'cc' => 'credit card'
836 | ],
837 | ],
838 |
839 | > **Warning**
840 | > By default, the Laravel application skeleton does not include the `lang` directory. If you would like to customize Laravel's language files, you may publish them via the `lang:publish` Artisan command.
841 |
842 | After defining this value, the validation rule will produce the following error message:
843 |
844 | ```none
845 | The credit card number field is required when payment type is credit card.
846 | ```
847 |
848 |
849 | ## Available Validation Rules
850 |
851 | Below is a list of all available validation rules and their function:
852 |
853 |
865 |
866 |
867 |
868 | [Accepted](#rule-accepted)
869 | [Accepted If](#rule-accepted-if)
870 | [Active URL](#rule-active-url)
871 | [After (Date)](#rule-after)
872 | [After Or Equal (Date)](#rule-after-or-equal)
873 | [Alpha](#rule-alpha)
874 | [Alpha Dash](#rule-alpha-dash)
875 | [Alpha Numeric](#rule-alpha-num)
876 | [Array](#rule-array)
877 | [Ascii](#rule-ascii)
878 | [Bail](#rule-bail)
879 | [Before (Date)](#rule-before)
880 | [Before Or Equal (Date)](#rule-before-or-equal)
881 | [Between](#rule-between)
882 | [Boolean](#rule-boolean)
883 | [Confirmed](#rule-confirmed)
884 | [Current Password](#rule-current-password)
885 | [Date](#rule-date)
886 | [Date Equals](#rule-date-equals)
887 | [Date Format](#rule-date-format)
888 | [Decimal](#rule-decimal)
889 | [Declined](#rule-declined)
890 | [Declined If](#rule-declined-if)
891 | [Different](#rule-different)
892 | [Digits](#rule-digits)
893 | [Digits Between](#rule-digits-between)
894 | [Dimensions (Image Files)](#rule-dimensions)
895 | [Distinct](#rule-distinct)
896 | [Doesnt Start With](#rule-doesnt-start-with)
897 | [Doesnt End With](#rule-doesnt-end-with)
898 | [Email](#rule-email)
899 | [Ends With](#rule-ends-with)
900 | [Enum](#rule-enum)
901 | [Exclude](#rule-exclude)
902 | [Exclude If](#rule-exclude-if)
903 | [Exclude Unless](#rule-exclude-unless)
904 | [Exclude With](#rule-exclude-with)
905 | [Exclude Without](#rule-exclude-without)
906 | [Exists (Database)](#rule-exists)
907 | [File](#rule-file)
908 | [Filled](#rule-filled)
909 | [Greater Than](#rule-gt)
910 | [Greater Than Or Equal](#rule-gte)
911 | [Image (File)](#rule-image)
912 | [In](#rule-in)
913 | [In Array](#rule-in-array)
914 | [Integer](#rule-integer)
915 | [IP Address](#rule-ip)
916 | [JSON](#rule-json)
917 | [Less Than](#rule-lt)
918 | [Less Than Or Equal](#rule-lte)
919 | [Lowercase](#rule-lowercase)
920 | [MAC Address](#rule-mac)
921 | [Max](#rule-max)
922 | [Max Digits](#rule-max-digits)
923 | [MIME Types](#rule-mimetypes)
924 | [MIME Type By File Extension](#rule-mimes)
925 | [Min](#rule-min)
926 | [Min Digits](#rule-min-digits)
927 | [Missing](#rule-missing)
928 | [Missing If](#rule-missing-if)
929 | [Missing Unless](#rule-missing-unless)
930 | [Missing With](#rule-missing-with)
931 | [Missing With All](#rule-missing-with-all)
932 | [Multiple Of](#rule-multiple-of)
933 | [Not In](#rule-not-in)
934 | [Not Regex](#rule-not-regex)
935 | [Nullable](#rule-nullable)
936 | [Numeric](#rule-numeric)
937 | [Password](#rule-password)
938 | [Present](#rule-present)
939 | [Prohibited](#rule-prohibited)
940 | [Prohibited If](#rule-prohibited-if)
941 | [Prohibited Unless](#rule-prohibited-unless)
942 | [Prohibits](#rule-prohibits)
943 | [Regular Expression](#rule-regex)
944 | [Required](#rule-required)
945 | [Required If](#rule-required-if)
946 | [Required Unless](#rule-required-unless)
947 | [Required With](#rule-required-with)
948 | [Required With All](#rule-required-with-all)
949 | [Required Without](#rule-required-without)
950 | [Required Without All](#rule-required-without-all)
951 | [Required Array Keys](#rule-required-array-keys)
952 | [Same](#rule-same)
953 | [Size](#rule-size)
954 | [Sometimes](#validating-when-present)
955 | [Starts With](#rule-starts-with)
956 | [String](#rule-string)
957 | [Timezone](#rule-timezone)
958 | [Unique (Database)](#rule-unique)
959 | [Uppercase](#rule-uppercase)
960 | [URL](#rule-url)
961 | [ULID](#rule-ulid)
962 | [UUID](#rule-uuid)
963 |
964 |
965 |
966 |
967 | #### accepted
968 |
969 | The field under validation must be `"yes"`, `"on"`, `1`, or `true`. This is useful for validating "Terms of Service" acceptance or similar fields.
970 |
971 |
972 | #### accepted_if:anotherfield,value,...
973 |
974 | The field under validation must be `"yes"`, `"on"`, `1`, or `true` if another field under validation is equal to a specified value. This is useful for validating "Terms of Service" acceptance or similar fields.
975 |
976 |
977 | #### active_url
978 |
979 | The field under validation must have a valid A or AAAA record according to the `dns_get_record` PHP function. The hostname of the provided URL is extracted using the `parse_url` PHP function before being passed to `dns_get_record`.
980 |
981 |
982 | #### after:_date_
983 |
984 | The field under validation must be a value after a given date. The dates will be passed into the `strtotime` PHP function in order to be converted to a valid `DateTime` instance:
985 |
986 | 'start_date' => 'required|date|after:tomorrow'
987 |
988 | Instead of passing a date string to be evaluated by `strtotime`, you may specify another field to compare against the date:
989 |
990 | 'finish_date' => 'required|date|after:start_date'
991 |
992 |
993 | #### after\_or\_equal:_date_
994 |
995 | The field under validation must be a value after or equal to the given date. For more information, see the [after](#rule-after) rule.
996 |
997 |
998 | #### alpha
999 |
1000 | The field under validation must be entirely Unicode alphabetic characters contained in [`\p{L}`](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AL%3A%5D&g=&i=) and [`\p{M}`](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AM%3A%5D&g=&i=).
1001 |
1002 | To restrict this validation rule to characters in the ASCII range (`a-z` and `A-Z`), you may provide the `ascii` option to the validation rule:
1003 |
1004 | ```php
1005 | 'username' => 'alpha:ascii',
1006 | ```
1007 |
1008 |
1009 | #### alpha_dash
1010 |
1011 | The field under validation must be entirely Unicode alpha-numeric characters contained in [`\p{L}`](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AL%3A%5D&g=&i=), [`\p{M}`](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AM%3A%5D&g=&i=), [`\p{N}`](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AN%3A%5D&g=&i=), as well as ASCII dashes (`-`) and ASCII underscores (`_`).
1012 |
1013 | To restrict this validation rule to characters in the ASCII range (`a-z` and `A-Z`), you may provide the `ascii` option to the validation rule:
1014 |
1015 | ```php
1016 | 'username' => 'alpha_dash:ascii',
1017 | ```
1018 |
1019 |
1020 | #### alpha_num
1021 |
1022 | The field under validation must be entirely Unicode alpha-numeric characters contained in [`\p{L}`](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AL%3A%5D&g=&i=), [`\p{M}`](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AM%3A%5D&g=&i=), and [`\p{N}`](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AN%3A%5D&g=&i=).
1023 |
1024 | To restrict this validation rule to characters in the ASCII range (`a-z` and `A-Z`), you may provide the `ascii` option to the validation rule:
1025 |
1026 | ```php
1027 | 'username' => 'alpha_num:ascii',
1028 | ```
1029 |
1030 |
1031 | #### array
1032 |
1033 | The field under validation must be a PHP `array`.
1034 |
1035 | When additional values are provided to the `array` rule, each key in the input array must be present within the list of values provided to the rule. In the following example, the `admin` key in the input array is invalid since it is not contained in the list of values provided to the `array` rule:
1036 |
1037 | use Illuminate\Support\Facades\Validator;
1038 |
1039 | $input = [
1040 | 'user' => [
1041 | 'name' => 'Taylor Otwell',
1042 | 'username' => 'taylorotwell',
1043 | 'admin' => true,
1044 | ],
1045 | ];
1046 |
1047 | Validator::make($input, [
1048 | 'user' => 'array:name,username',
1049 | ]);
1050 |
1051 | In general, you should always specify the array keys that are allowed to be present within your array.
1052 |
1053 |
1054 | #### ascii
1055 |
1056 | The field under validation must be entirely 7-bit ASCII characters.
1057 |
1058 |
1059 | #### bail
1060 |
1061 | Stop running validation rules for the field after the first validation failure.
1062 |
1063 | While the `bail` rule will only stop validating a specific field when it encounters a validation failure, the `stopOnFirstFailure` method will inform the validator that it should stop validating all attributes once a single validation failure has occurred:
1064 |
1065 | if ($validator->stopOnFirstFailure()->fails()) {
1066 | // ...
1067 | }
1068 |
1069 |
1070 | #### before:_date_
1071 |
1072 | The field under validation must be a value preceding the given date. The dates will be passed into the PHP `strtotime` function in order to be converted into a valid `DateTime` instance. In addition, like the [`after`](#rule-after) rule, the name of another field under validation may be supplied as the value of `date`.
1073 |
1074 |
1075 | #### before\_or\_equal:_date_
1076 |
1077 | The field under validation must be a value preceding or equal to the given date. The dates will be passed into the PHP `strtotime` function in order to be converted into a valid `DateTime` instance. In addition, like the [`after`](#rule-after) rule, the name of another field under validation may be supplied as the value of `date`.
1078 |
1079 |
1080 | #### between:_min_,_max_
1081 |
1082 | The field under validation must have a size between the given _min_ and _max_ (inclusive). Strings, numerics, arrays, and files are evaluated in the same fashion as the [`size`](#rule-size) rule.
1083 |
1084 |
1085 | #### boolean
1086 |
1087 | The field under validation must be able to be cast as a boolean. Accepted input are `true`, `false`, `1`, `0`, `"1"`, and `"0"`.
1088 |
1089 |
1090 | #### confirmed
1091 |
1092 | The field under validation must have a matching field of `{field}_confirmation`. For example, if the field under validation is `password`, a matching `password_confirmation` field must be present in the input.
1093 |
1094 |
1095 | #### current_password
1096 |
1097 | The field under validation must match the authenticated user's password. You may specify an [authentication guard](/docs/{{version}}/authentication) using the rule's first parameter:
1098 |
1099 | 'password' => 'current_password:api'
1100 |
1101 |
1102 | #### date
1103 |
1104 | The field under validation must be a valid, non-relative date according to the `strtotime` PHP function.
1105 |
1106 |
1107 | #### date_equals:_date_
1108 |
1109 | The field under validation must be equal to the given date. The dates will be passed into the PHP `strtotime` function in order to be converted into a valid `DateTime` instance.
1110 |
1111 |
1112 | #### date_format:_format_,...
1113 |
1114 | The field under validation must match one of the given _formats_. You should use **either** `date` or `date_format` when validating a field, not both. This validation rule supports all formats supported by PHP's [DateTime](https://www.php.net/manual/en/class.datetime.php) class.
1115 |
1116 |
1117 | #### decimal:_min_,_max_
1118 |
1119 | The field under validation must be numeric and must contain the specified number of decimal places:
1120 |
1121 | // Must have exactly two decimal places (9.99)...
1122 | 'price' => 'decimal:2'
1123 |
1124 | // Must have between 2 and 4 decimal places...
1125 | 'price' => 'decimal:2,4'
1126 |
1127 |
1128 | #### declined
1129 |
1130 | The field under validation must be `"no"`, `"off"`, `0`, or `false`.
1131 |
1132 |
1133 | #### declined_if:anotherfield,value,...
1134 |
1135 | The field under validation must be `"no"`, `"off"`, `0`, or `false` if another field under validation is equal to a specified value.
1136 |
1137 |
1138 | #### different:_field_
1139 |
1140 | The field under validation must have a different value than _field_.
1141 |
1142 |
1143 | #### digits:_value_
1144 |
1145 | The integer under validation must have an exact length of _value_.
1146 |
1147 |
1148 | #### digits_between:_min_,_max_
1149 |
1150 | The integer validation must have a length between the given _min_ and _max_.
1151 |
1152 |
1153 | #### dimensions
1154 |
1155 | The file under validation must be an image meeting the dimension constraints as specified by the rule's parameters:
1156 |
1157 | 'avatar' => 'dimensions:min_width=100,min_height=200'
1158 |
1159 | Available constraints are: _min\_width_, _max\_width_, _min\_height_, _max\_height_, _width_, _height_, _ratio_.
1160 |
1161 | A _ratio_ constraint should be represented as width divided by height. This can be specified either by a fraction like `3/2` or a float like `1.5`:
1162 |
1163 | 'avatar' => 'dimensions:ratio=3/2'
1164 |
1165 | Since this rule requires several arguments, you may use the `Rule::dimensions` method to fluently construct the rule:
1166 |
1167 | use Illuminate\Support\Facades\Validator;
1168 | use Illuminate\Validation\Rule;
1169 |
1170 | Validator::make($data, [
1171 | 'avatar' => [
1172 | 'required',
1173 | Rule::dimensions()->maxWidth(1000)->maxHeight(500)->ratio(3 / 2),
1174 | ],
1175 | ]);
1176 |
1177 |
1178 | #### distinct
1179 |
1180 | When validating arrays, the field under validation must not have any duplicate values:
1181 |
1182 | 'foo.*.id' => 'distinct'
1183 |
1184 | Distinct uses loose variable comparisons by default. To use strict comparisons, you may add the `strict` parameter to your validation rule definition:
1185 |
1186 | 'foo.*.id' => 'distinct:strict'
1187 |
1188 | You may add `ignore_case` to the validation rule's arguments to make the rule ignore capitalization differences:
1189 |
1190 | 'foo.*.id' => 'distinct:ignore_case'
1191 |
1192 |
1193 | #### doesnt_start_with:_foo_,_bar_,...
1194 |
1195 | The field under validation must not start with one of the given values.
1196 |
1197 |
1198 | #### doesnt_end_with:_foo_,_bar_,...
1199 |
1200 | The field under validation must not end with one of the given values.
1201 |
1202 |
1203 | #### email
1204 |
1205 | The field under validation must be formatted as an email address. This validation rule utilizes the [`egulias/email-validator`](https://github.com/egulias/EmailValidator) package for validating the email address. By default, the `RFCValidation` validator is applied, but you can apply other validation styles as well:
1206 |
1207 | 'email' => 'email:rfc,dns'
1208 |
1209 | The example above will apply the `RFCValidation` and `DNSCheckValidation` validations. Here's a full list of validation styles you can apply:
1210 |
1211 |
1212 |
1213 | - `rfc`: `RFCValidation`
1214 | - `strict`: `NoRFCWarningsValidation`
1215 | - `dns`: `DNSCheckValidation`
1216 | - `spoof`: `SpoofCheckValidation`
1217 | - `filter`: `FilterEmailValidation`
1218 | - `filter_unicode`: `FilterEmailValidation::unicode()`
1219 |
1220 |
1221 |
1222 | The `filter` validator, which uses PHP's `filter_var` function, ships with Laravel and was Laravel's default email validation behavior prior to Laravel version 5.8.
1223 |
1224 | > **Warning**
1225 | > The `dns` and `spoof` validators require the PHP `intl` extension.
1226 |
1227 |
1228 | #### ends_with:_foo_,_bar_,...
1229 |
1230 | The field under validation must end with one of the given values.
1231 |
1232 |
1233 | #### enum
1234 |
1235 | The `Enum` rule is a class based rule that validates whether the field under validation contains a valid enum value. The `Enum` rule accepts the name of the enum as its only constructor argument:
1236 |
1237 | use App\Enums\ServerStatus;
1238 | use Illuminate\Validation\Rules\Enum;
1239 |
1240 | $request->validate([
1241 | 'status' => [new Enum(ServerStatus::class)],
1242 | ]);
1243 |
1244 |
1245 | #### exclude
1246 |
1247 | The field under validation will be excluded from the request data returned by the `validate` and `validated` methods.
1248 |
1249 |
1250 | #### exclude_if:_anotherfield_,_value_
1251 |
1252 | The field under validation will be excluded from the request data returned by the `validate` and `validated` methods if the _anotherfield_ field is equal to _value_.
1253 |
1254 | If complex conditional exclusion logic is required, you may utilize the `Rule::excludeIf` method. This method accepts a boolean or a closure. When given a closure, the closure should return `true` or `false` to indicate if the field under validation should be excluded:
1255 |
1256 | use Illuminate\Support\Facades\Validator;
1257 | use Illuminate\Validation\Rule;
1258 |
1259 | Validator::make($request->all(), [
1260 | 'role_id' => Rule::excludeIf($request->user()->is_admin),
1261 | ]);
1262 |
1263 | Validator::make($request->all(), [
1264 | 'role_id' => Rule::excludeIf(fn () => $request->user()->is_admin),
1265 | ]);
1266 |
1267 |
1268 | #### exclude_unless:_anotherfield_,_value_
1269 |
1270 | The field under validation will be excluded from the request data returned by the `validate` and `validated` methods unless _anotherfield_'s field is equal to _value_. If _value_ is `null` (`exclude_unless:name,null`), the field under validation will be excluded unless the comparison field is `null` or the comparison field is missing from the request data.
1271 |
1272 |
1273 | #### exclude_with:_anotherfield_
1274 |
1275 | The field under validation will be excluded from the request data returned by the `validate` and `validated` methods if the _anotherfield_ field is present.
1276 |
1277 |
1278 | #### exclude_without:_anotherfield_
1279 |
1280 | The field under validation will be excluded from the request data returned by the `validate` and `validated` methods if the _anotherfield_ field is not present.
1281 |
1282 |
1283 | #### exists:_table_,_column_
1284 |
1285 | The field under validation must exist in a given database table.
1286 |
1287 |
1288 | #### Basic Usage Of Exists Rule
1289 |
1290 | 'state' => 'exists:states'
1291 |
1292 | If the `column` option is not specified, the field name will be used. So, in this case, the rule will validate that the `states` database table contains a record with a `state` column value matching the request's `state` attribute value.
1293 |
1294 |
1295 | #### Specifying A Custom Column Name
1296 |
1297 | You may explicitly specify the database column name that should be used by the validation rule by placing it after the database table name:
1298 |
1299 | 'state' => 'exists:states,abbreviation'
1300 |
1301 | 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:
1302 |
1303 | 'email' => 'exists:connection.staff,email'
1304 |
1305 | Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name:
1306 |
1307 | 'user_id' => 'exists:App\Models\User,id'
1308 |
1309 | 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:
1310 |
1311 | use Illuminate\Database\Query\Builder;
1312 | use Illuminate\Support\Facades\Validator;
1313 | use Illuminate\Validation\Rule;
1314 |
1315 | Validator::make($data, [
1316 | 'email' => [
1317 | 'required',
1318 | Rule::exists('staff')->where(function (Builder $query) {
1319 | return $query->where('account_id', 1);
1320 | }),
1321 | ],
1322 | ]);
1323 |
1324 | You may explicitly specify the database column name that should be used by the `exists` rule generated by the `Rule::exists` method by providing the column name as the second argument to the `exists` method:
1325 |
1326 | 'state' => Rule::exists('states', 'abbreviation'),
1327 |
1328 |
1329 | #### file
1330 |
1331 | The field under validation must be a successfully uploaded file.
1332 |
1333 |
1334 | #### filled
1335 |
1336 | The field under validation must not be empty when it is present.
1337 |
1338 |
1339 | #### gt:_field_
1340 |
1341 | The field under validation must be greater than the given _field_. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the [`size`](#rule-size) rule.
1342 |
1343 |
1344 | #### gte:_field_
1345 |
1346 | The field under validation must be greater than or equal to the given _field_. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the [`size`](#rule-size) rule.
1347 |
1348 |
1349 | #### image
1350 |
1351 | The file under validation must be an image (jpg, jpeg, png, bmp, gif, svg, or webp).
1352 |
1353 |
1354 | #### in:_foo_,_bar_,...
1355 |
1356 | The field under validation must be included in the given list of values. Since this rule often requires you to `implode` an array, the `Rule::in` method may be used to fluently construct the rule:
1357 |
1358 | use Illuminate\Support\Facades\Validator;
1359 | use Illuminate\Validation\Rule;
1360 |
1361 | Validator::make($data, [
1362 | 'zones' => [
1363 | 'required',
1364 | Rule::in(['first-zone', 'second-zone']),
1365 | ],
1366 | ]);
1367 |
1368 | When the `in` rule is combined with the `array` rule, each value in the input array must be present within the list of values provided to the `in` rule. In the following example, the `LAS` airport code in the input array is invalid since it is not contained in the list of airports provided to the `in` rule:
1369 |
1370 | use Illuminate\Support\Facades\Validator;
1371 | use Illuminate\Validation\Rule;
1372 |
1373 | $input = [
1374 | 'airports' => ['NYC', 'LAS'],
1375 | ];
1376 |
1377 | Validator::make($input, [
1378 | 'airports' => [
1379 | 'required',
1380 | 'array',
1381 | ],
1382 | 'airports.*' => Rule::in(['NYC', 'LIT']),
1383 | ]);
1384 |
1385 |
1386 | #### in_array:_anotherfield_.*
1387 |
1388 | The field under validation must exist in _anotherfield_'s values.
1389 |
1390 |
1391 | #### integer
1392 |
1393 | The field under validation must be an integer.
1394 |
1395 | > **Warning**
1396 | > This validation rule does not verify that the input is of the "integer" variable type, only that the input is of a type accepted by PHP's `FILTER_VALIDATE_INT` rule. If you need to validate the input as being a number please use this rule in combination with [the `numeric` validation rule](#rule-numeric).
1397 |
1398 |
1399 | #### ip
1400 |
1401 | The field under validation must be an IP address.
1402 |
1403 |
1404 | #### ipv4
1405 |
1406 | The field under validation must be an IPv4 address.
1407 |
1408 |
1409 | #### ipv6
1410 |
1411 | The field under validation must be an IPv6 address.
1412 |
1413 |
1414 | #### json
1415 |
1416 | The field under validation must be a valid JSON string.
1417 |
1418 |
1419 | #### lt:_field_
1420 |
1421 | The field under validation must be less than the given _field_. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the [`size`](#rule-size) rule.
1422 |
1423 |
1424 | #### lte:_field_
1425 |
1426 | The field under validation must be less than or equal to the given _field_. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the [`size`](#rule-size) rule.
1427 |
1428 |
1429 | #### lowercase
1430 |
1431 | The field under validation must be lowercase.
1432 |
1433 |
1434 | #### mac_address
1435 |
1436 | The field under validation must be a MAC address.
1437 |
1438 |
1439 | #### max:_value_
1440 |
1441 | The field under validation must be less than or equal to a maximum _value_. Strings, numerics, arrays, and files are evaluated in the same fashion as the [`size`](#rule-size) rule.
1442 |
1443 |
1444 | #### max_digits:_value_
1445 |
1446 | The integer under validation must have a maximum length of _value_.
1447 |
1448 |
1449 | #### mimetypes:_text/plain_,...
1450 |
1451 | The file under validation must match one of the given MIME types:
1452 |
1453 | 'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime'
1454 |
1455 | 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's provided MIME type.
1456 |
1457 |
1458 | #### mimes:_foo_,_bar_,...
1459 |
1460 | The file under validation must have a MIME type corresponding to one of the listed extensions.
1461 |
1462 |
1463 | #### Basic Usage Of MIME Rule
1464 |
1465 | 'photo' => 'mimes:jpg,bmp,png'
1466 |
1467 | Even though you only need to specify the extensions, this rule actually validates 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:
1468 |
1469 | [https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types](https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types)
1470 |
1471 |
1472 | #### min:_value_
1473 |
1474 | The field under validation must have a minimum _value_. Strings, numerics, arrays, and files are evaluated in the same fashion as the [`size`](#rule-size) rule.
1475 |
1476 |
1477 | #### min_digits:_value_
1478 |
1479 | The integer under validation must have a minimum length of _value_.
1480 |
1481 |
1482 | #### multiple_of:_value_
1483 |
1484 | The field under validation must be a multiple of _value_.
1485 |
1486 |
1487 | #### missing
1488 |
1489 | The field under validation must not be present in the input data.
1490 |
1491 |
1492 | #### missing_if:_anotherfield_,_value_,...
1493 |
1494 | The field under validation must not be present if the _anotherfield_ field is equal to any _value_.
1495 |
1496 |
1497 | #### missing_unless:_anotherfield_,_value_
1498 |
1499 | The field under validation must not be present unless the _anotherfield_ field is equal to any _value_.
1500 |
1501 |
1502 | #### missing_with:_foo_,_bar_,...
1503 |
1504 | The field under validation must not be present _only if_ any of the other specified fields are present.
1505 |
1506 |
1507 | #### missing_with_all:_foo_,_bar_,...
1508 |
1509 | The field under validation must not be present _only if_ all of the other specified fields are present.
1510 |
1511 |
1512 | #### not_in:_foo_,_bar_,...
1513 |
1514 | The field under validation must not be included in the given list of values. The `Rule::notIn` method may be used to fluently construct the rule:
1515 |
1516 | use Illuminate\Validation\Rule;
1517 |
1518 | Validator::make($data, [
1519 | 'toppings' => [
1520 | 'required',
1521 | Rule::notIn(['sprinkles', 'cherries']),
1522 | ],
1523 | ]);
1524 |
1525 |
1526 | #### not_regex:_pattern_
1527 |
1528 | The field under validation must not match the given regular expression.
1529 |
1530 | Internally, this rule uses the PHP `preg_match` function. The pattern specified should obey the same formatting required by `preg_match` and thus also include valid delimiters. For example: `'email' => 'not_regex:/^.+$/i'`.
1531 |
1532 | > **Warning**
1533 | > When using the `regex` / `not_regex` patterns, it may be necessary to specify your validation rules using an array instead of using `|` delimiters, especially if the regular expression contains a `|` character.
1534 |
1535 |
1536 | #### nullable
1537 |
1538 | The field under validation may be `null`.
1539 |
1540 |
1541 | #### numeric
1542 |
1543 | The field under validation must be [numeric](https://www.php.net/manual/en/function.is-numeric.php).
1544 |
1545 |
1546 | #### password
1547 |
1548 | The field under validation must match the authenticated user's password.
1549 |
1550 | > **Warning**
1551 | > This rule was renamed to `current_password` with the intention of removing it in Laravel 9. Please use the [Current Password](#rule-current-password) rule instead.
1552 |
1553 |
1554 | #### present
1555 |
1556 | The field under validation must exist in the input data.
1557 |
1558 |
1559 | #### prohibited
1560 |
1561 | The field under validation must be missing or empty. A field is "empty" if it meets one of the following criteria:
1562 |
1563 |
1564 |
1565 | - The value is `null`.
1566 | - The value is an empty string.
1567 | - The value is an empty array or empty `Countable` object.
1568 | - The value is an uploaded file with an empty path.
1569 |
1570 |
1571 |
1572 |
1573 | #### prohibited_if:_anotherfield_,_value_,...
1574 |
1575 | The field under validation must be missing or empty if the _anotherfield_ field is equal to any _value_. A field is "empty" if it meets one of the following criteria:
1576 |
1577 |
1578 |
1579 | - The value is `null`.
1580 | - The value is an empty string.
1581 | - The value is an empty array or empty `Countable` object.
1582 | - The value is an uploaded file with an empty path.
1583 |
1584 |
1585 |
1586 | If complex conditional prohibition logic is required, you may utilize the `Rule::prohibitedIf` method. This method accepts a boolean or a closure. When given a closure, the closure should return `true` or `false` to indicate if the field under validation should be prohibited:
1587 |
1588 | use Illuminate\Support\Facades\Validator;
1589 | use Illuminate\Validation\Rule;
1590 |
1591 | Validator::make($request->all(), [
1592 | 'role_id' => Rule::prohibitedIf($request->user()->is_admin),
1593 | ]);
1594 |
1595 | Validator::make($request->all(), [
1596 | 'role_id' => Rule::prohibitedIf(fn () => $request->user()->is_admin),
1597 | ]);
1598 |
1599 |
1600 | #### prohibited_unless:_anotherfield_,_value_,...
1601 |
1602 | The field under validation must be missing or empty unless the _anotherfield_ field is equal to any _value_. A field is "empty" if it meets one of the following criteria:
1603 |
1604 |
1605 |
1606 | - The value is `null`.
1607 | - The value is an empty string.
1608 | - The value is an empty array or empty `Countable` object.
1609 | - The value is an uploaded file with an empty path.
1610 |
1611 |
1612 |
1613 |
1614 | #### prohibits:_anotherfield_,...
1615 |
1616 | If the field under validation is not missing or empty, all fields in _anotherfield_ must be missing or empty. A field is "empty" if it meets one of the following criteria:
1617 |
1618 |
1619 |
1620 | - The value is `null`.
1621 | - The value is an empty string.
1622 | - The value is an empty array or empty `Countable` object.
1623 | - The value is an uploaded file with an empty path.
1624 |
1625 |
1626 |
1627 |
1628 | #### regex:_pattern_
1629 |
1630 | The field under validation must match the given regular expression.
1631 |
1632 | Internally, this rule uses the PHP `preg_match` function. The pattern specified should obey the same formatting required by `preg_match` and thus also include valid delimiters. For example: `'email' => 'regex:/^.+@.+$/i'`.
1633 |
1634 | > **Warning**
1635 | > When using the `regex` / `not_regex` patterns, it may be necessary to specify rules in an array instead of using `|` delimiters, especially if the regular expression contains a `|` character.
1636 |
1637 |
1638 | #### required
1639 |
1640 | The field under validation must be present in the input data and not empty. A field is "empty" if it meets one of the following criteria:
1641 |
1642 |
1643 |
1644 | - The value is `null`.
1645 | - The value is an empty string.
1646 | - The value is an empty array or empty `Countable` object.
1647 | - The value is an uploaded file with no path.
1648 |
1649 |
1650 |
1651 |
1652 | #### required_if:_anotherfield_,_value_,...
1653 |
1654 | The field under validation must be present and not empty if the _anotherfield_ field is equal to any _value_.
1655 |
1656 | If you would like to construct a more complex condition for the `required_if` rule, you may use the `Rule::requiredIf` method. This method accepts a boolean or a closure. When passed a closure, the closure should return `true` or `false` to indicate if the field under validation is required:
1657 |
1658 | use Illuminate\Support\Facades\Validator;
1659 | use Illuminate\Validation\Rule;
1660 |
1661 | Validator::make($request->all(), [
1662 | 'role_id' => Rule::requiredIf($request->user()->is_admin),
1663 | ]);
1664 |
1665 | Validator::make($request->all(), [
1666 | 'role_id' => Rule::requiredIf(fn () => $request->user()->is_admin),
1667 | ]);
1668 |
1669 |
1670 | #### required_unless:_anotherfield_,_value_,...
1671 |
1672 | The field under validation must be present and not empty unless the _anotherfield_ field is equal to any _value_. This also means _anotherfield_ must be present in the request data unless _value_ is `null`. If _value_ is `null` (`required_unless:name,null`), the field under validation will be required unless the comparison field is `null` or the comparison field is missing from the request data.
1673 |
1674 |
1675 | #### required_with:_foo_,_bar_,...
1676 |
1677 | The field under validation must be present and not empty _only if_ any of the other specified fields are present and not empty.
1678 |
1679 |
1680 | #### required_with_all:_foo_,_bar_,...
1681 |
1682 | The field under validation must be present and not empty _only if_ all of the other specified fields are present and not empty.
1683 |
1684 |
1685 | #### required_without:_foo_,_bar_,...
1686 |
1687 | The field under validation must be present and not empty _only when_ any of the other specified fields are empty or not present.
1688 |
1689 |
1690 | #### required_without_all:_foo_,_bar_,...
1691 |
1692 | The field under validation must be present and not empty _only when_ all of the other specified fields are empty or not present.
1693 |
1694 |
1695 | #### required_array_keys:_foo_,_bar_,...
1696 |
1697 | The field under validation must be an array and must contain at least the specified keys.
1698 |
1699 |
1700 | #### same:_field_
1701 |
1702 | The given _field_ must match the field under validation.
1703 |
1704 |
1705 | #### size:_value_
1706 |
1707 | 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 (the attribute must also have the `numeric` or `integer` rule). For an array, _size_ corresponds to the `count` of the array. For files, _size_ corresponds to the file size in kilobytes. Let's look at some examples:
1708 |
1709 | // Validate that a string is exactly 12 characters long...
1710 | 'title' => 'size:12';
1711 |
1712 | // Validate that a provided integer equals 10...
1713 | 'seats' => 'integer|size:10';
1714 |
1715 | // Validate that an array has exactly 5 elements...
1716 | 'tags' => 'array|size:5';
1717 |
1718 | // Validate that an uploaded file is exactly 512 kilobytes...
1719 | 'image' => 'file|size:512';
1720 |
1721 |
1722 | #### starts_with:_foo_,_bar_,...
1723 |
1724 | The field under validation must start with one of the given values.
1725 |
1726 |
1727 | #### string
1728 |
1729 | 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.
1730 |
1731 |
1732 | #### timezone
1733 |
1734 | The field under validation must be a valid timezone identifier according to the `DateTimeZone::listIdentifiers` method.
1735 |
1736 | The arguments [accepted by the `DateTimeZone::listIdentifiers` method](https://www.php.net/manual/en/datetimezone.listidentifiers.php) may also be provided to this validation rule:
1737 |
1738 | 'timezone' => 'required|timezone:all';
1739 |
1740 | 'timezone' => 'required|timezone:Africa';
1741 |
1742 | 'timezone' => 'required|timezone:per_country,US';
1743 |
1744 |
1745 | #### unique:_table_,_column_
1746 |
1747 | The field under validation must not exist within the given database table.
1748 |
1749 | **Specifying A Custom Table / Column Name:**
1750 |
1751 | Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name:
1752 |
1753 | 'email' => 'unique:App\Models\User,email_address'
1754 |
1755 | The `column` option may be used to specify the field's corresponding database column. If the `column` option is not specified, the name of the field under validation will be used.
1756 |
1757 | 'email' => 'unique:users,email_address'
1758 |
1759 | **Specifying A Custom Database Connection**
1760 |
1761 | Occasionally, you may need to set a custom connection for database queries made by the Validator. To accomplish this, you may prepend the connection name to the table name:
1762 |
1763 | 'email' => 'unique:connection.users,email_address'
1764 |
1765 | **Forcing A Unique Rule To Ignore A Given ID:**
1766 |
1767 | Sometimes, you may wish to ignore a given ID during unique validation. For example, consider an "update profile" screen that includes the user's name, email address, and location. You will probably want to verify that the email address is unique. However, if the user only changes the name field and not the email field, you do not want a validation error to be thrown because the user is already the owner of the email address in question.
1768 |
1769 | 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:
1770 |
1771 | use Illuminate\Support\Facades\Validator;
1772 | use Illuminate\Validation\Rule;
1773 |
1774 | Validator::make($data, [
1775 | 'email' => [
1776 | 'required',
1777 | Rule::unique('users')->ignore($user->id),
1778 | ],
1779 | ]);
1780 |
1781 | > **Warning**
1782 | > You should never pass any user controlled request input into the `ignore` method. Instead, you should only pass a system generated unique ID such as an auto-incrementing ID or UUID from an Eloquent model instance. Otherwise, your application will be vulnerable to an SQL injection attack.
1783 |
1784 | Instead of passing the model key's value to the `ignore` method, you may also pass the entire model instance. Laravel will automatically extract the key from the model:
1785 |
1786 | Rule::unique('users')->ignore($user)
1787 |
1788 | 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:
1789 |
1790 | Rule::unique('users')->ignore($user->id, 'user_id')
1791 |
1792 | By default, the `unique` rule will check the uniqueness of the column matching the name of the attribute being validated. However, you may pass a different column name as the second argument to the `unique` method:
1793 |
1794 | Rule::unique('users', 'email_address')->ignore($user->id)
1795 |
1796 | **Adding Additional Where Clauses:**
1797 |
1798 | You may specify additional query conditions by customizing the query using the `where` method. For example, let's add a query condition that scopes the query to only search records that have an `account_id` column value of `1`:
1799 |
1800 | 'email' => Rule::unique('users')->where(fn (Builder $query) => $query->where('account_id', 1))
1801 |
1802 |
1803 | #### uppercase
1804 |
1805 | The field under validation must be uppercase.
1806 |
1807 |
1808 | #### url
1809 |
1810 | The field under validation must be a valid URL.
1811 |
1812 |
1813 | #### ulid
1814 |
1815 | The field under validation must be a valid [Universally Unique Lexicographically Sortable Identifier](https://github.com/ulid/spec) (ULID).
1816 |
1817 |
1818 | #### uuid
1819 |
1820 | The field under validation must be a valid RFC 4122 (version 1, 3, 4, or 5) universally unique identifier (UUID).
1821 |
1822 |
1823 | ## Conditionally Adding Rules
1824 |
1825 |
1826 | #### Skipping Validation When Fields Have Certain Values
1827 |
1828 | You may occasionally wish to not validate a given field if another field has a given value. You may accomplish this using the `exclude_if` validation rule. In this example, the `appointment_date` and `doctor_name` fields will not be validated if the `has_appointment` field has a value of `false`:
1829 |
1830 | use Illuminate\Support\Facades\Validator;
1831 |
1832 | $validator = Validator::make($data, [
1833 | 'has_appointment' => 'required|boolean',
1834 | 'appointment_date' => 'exclude_if:has_appointment,false|required|date',
1835 | 'doctor_name' => 'exclude_if:has_appointment,false|required|string',
1836 | ]);
1837 |
1838 | Alternatively, you may use the `exclude_unless` rule to not validate a given field unless another field has a given value:
1839 |
1840 | $validator = Validator::make($data, [
1841 | 'has_appointment' => 'required|boolean',
1842 | 'appointment_date' => 'exclude_unless:has_appointment,true|required|date',
1843 | 'doctor_name' => 'exclude_unless:has_appointment,true|required|string',
1844 | ]);
1845 |
1846 |
1847 | #### Validating When Present
1848 |
1849 | In some situations, you may wish to run validation checks against a field **only** if that field is present in the data being validated. To quickly accomplish this, add the `sometimes` rule to your rule list:
1850 |
1851 | $v = Validator::make($data, [
1852 | 'email' => 'sometimes|required|email',
1853 | ]);
1854 |
1855 | In the example above, the `email` field will only be validated if it is present in the `$data` array.
1856 |
1857 | > **Note**
1858 | > If you are attempting to validate a field that should always be present but may be empty, check out [this note on optional fields](#a-note-on-optional-fields).
1859 |
1860 |
1861 | #### Complex Conditional Validation
1862 |
1863 | 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:
1864 |
1865 | use Illuminate\Support\Facades\Validator;
1866 |
1867 | $validator = Validator::make($request->all(), [
1868 | 'email' => 'required|email',
1869 | 'games' => 'required|numeric',
1870 | ]);
1871 |
1872 | 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 games. To conditionally add this requirement, we can use the `sometimes` method on the `Validator` instance.
1873 |
1874 | use Illuminate\Support\Fluent;
1875 |
1876 | $validator->sometimes('reason', 'required|max:500', function (Fluent $input) {
1877 | return $input->games >= 100;
1878 | });
1879 |
1880 | The first argument passed to the `sometimes` method is the name of the field we are conditionally validating. The second argument is a list of 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:
1881 |
1882 | $validator->sometimes(['reason', 'cost'], 'required', function (Fluent $input) {
1883 | return $input->games >= 100;
1884 | });
1885 |
1886 | > **Note**
1887 | > 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 under validation.
1888 |
1889 |
1890 | #### Complex Conditional Array Validation
1891 |
1892 | Sometimes you may want to validate a field based on another field in the same nested array whose index you do not know. In these situations, you may allow your closure to receive a second argument which will be the current individual item in the array being validated:
1893 |
1894 | $input = [
1895 | 'channels' => [
1896 | [
1897 | 'type' => 'email',
1898 | 'address' => 'abigail@example.com',
1899 | ],
1900 | [
1901 | 'type' => 'url',
1902 | 'address' => 'https://example.com',
1903 | ],
1904 | ],
1905 | ];
1906 |
1907 | $validator->sometimes('channels.*.address', 'email', function (Fluent $input, Fluent $item) {
1908 | return $item->type === 'email';
1909 | });
1910 |
1911 | $validator->sometimes('channels.*.address', 'url', function (Fluent $input, Fluent $item) {
1912 | return $item->type !== 'email';
1913 | });
1914 |
1915 | Like the `$input` parameter passed to the closure, the `$item` parameter is an instance of `Illuminate\Support\Fluent` when the attribute data is an array; otherwise, it is a string.
1916 |
1917 |
1918 | ## Validating Arrays
1919 |
1920 | As discussed in the [`array` validation rule documentation](#rule-array), the `array` rule accepts a list of allowed array keys. If any additional keys are present within the array, validation will fail:
1921 |
1922 | use Illuminate\Support\Facades\Validator;
1923 |
1924 | $input = [
1925 | 'user' => [
1926 | 'name' => 'Taylor Otwell',
1927 | 'username' => 'taylorotwell',
1928 | 'admin' => true,
1929 | ],
1930 | ];
1931 |
1932 | Validator::make($input, [
1933 | 'user' => 'array:name,username',
1934 | ]);
1935 |
1936 | In general, you should always specify the array keys that are allowed to be present within your array. Otherwise, the validator's `validate` and `validated` methods will return all of the validated data, including the array and all of its keys, even if those keys were not validated by other nested array validation rules.
1937 |
1938 |
1939 | ### Validating Nested Array Input
1940 |
1941 | Validating nested array based form input fields doesn't have to be a pain. You may use "dot notation" to validate attributes within an array. For example, if the incoming HTTP request contains a `photos[profile]` field, you may validate it like so:
1942 |
1943 | use Illuminate\Support\Facades\Validator;
1944 |
1945 | $validator = Validator::make($request->all(), [
1946 | 'photos.profile' => 'required|image',
1947 | ]);
1948 |
1949 | You may also validate each element of an array. For example, to validate that each email in a given array input field is unique, you may do the following:
1950 |
1951 | $validator = Validator::make($request->all(), [
1952 | 'person.*.email' => 'email|unique:users',
1953 | 'person.*.first_name' => 'required_with:person.*.last_name',
1954 | ]);
1955 |
1956 | Likewise, you may use the `*` character when specifying [custom validation messages in your language files](#custom-messages-for-specific-attributes), making it a breeze to use a single validation message for array based fields:
1957 |
1958 | 'custom' => [
1959 | 'person.*.email' => [
1960 | 'unique' => 'Each person must have a unique email address',
1961 | ]
1962 | ],
1963 |
1964 |
1965 | #### Accessing Nested Array Data
1966 |
1967 | Sometimes you may need to access the value for a given nested array element when assigning validation rules to the attribute. You may accomplish this using the `Rule::forEach` method. The `forEach` method accepts a closure that will be invoked for each iteration of the array attribute under validation and will receive the attribute's value and explicit, fully-expanded attribute name. The closure should return an array of rules to assign to the array element:
1968 |
1969 | use App\Rules\HasPermission;
1970 | use Illuminate\Support\Facades\Validator;
1971 | use Illuminate\Validation\Rule;
1972 |
1973 | $validator = Validator::make($request->all(), [
1974 | 'companies.*.id' => Rule::forEach(function (string|null $value, string $attribute) {
1975 | return [
1976 | Rule::exists(Company::class, 'id'),
1977 | new HasPermission('manage-company', $value),
1978 | ];
1979 | }),
1980 | ]);
1981 |
1982 |
1983 | ### Error Message Indexes & Positions
1984 |
1985 | When validating arrays, you may want to reference the index or position of a particular item that failed validation within the error message displayed by your application. To accomplish this, you may include the `:index` (starts from `0`) and `:position` (starts from `1`) placeholders within your [custom validation message](#manual-customizing-the-error-messages):
1986 |
1987 | use Illuminate\Support\Facades\Validator;
1988 |
1989 | $input = [
1990 | 'photos' => [
1991 | [
1992 | 'name' => 'BeachVacation.jpg',
1993 | 'description' => 'A photo of my beach vacation!',
1994 | ],
1995 | [
1996 | 'name' => 'GrandCanyon.jpg',
1997 | 'description' => '',
1998 | ],
1999 | ],
2000 | ];
2001 |
2002 | Validator::validate($input, [
2003 | 'photos.*.description' => 'required',
2004 | ], [
2005 | 'photos.*.description.required' => 'Please describe photo #:position.',
2006 | ]);
2007 |
2008 | Given the example above, validation will fail and the user will be presented with the following error of _"Please describe photo #2."_
2009 |
2010 |
2011 | ## Validating Files
2012 |
2013 | Laravel provides a variety of validation rules that may be used to validate uploaded files, such as `mimes`, `image`, `min`, and `max`. While you are free to specify these rules individually when validating files, Laravel also offers a fluent file validation rule builder that you may find convenient:
2014 |
2015 | use Illuminate\Support\Facades\Validator;
2016 | use Illuminate\Validation\Rules\File;
2017 |
2018 | Validator::validate($input, [
2019 | 'attachment' => [
2020 | 'required',
2021 | File::types(['mp3', 'wav'])
2022 | ->min(1024)
2023 | ->max(12 * 1024),
2024 | ],
2025 | ]);
2026 |
2027 | If your application accepts images uploaded by your users, you may use the `File` rule's `image` constructor method to indicate that the uploaded file should be an image. In addition, the `dimensions` rule may be used to limit the dimensions of the image:
2028 |
2029 | use Illuminate\Support\Facades\Validator;
2030 | use Illuminate\Validation\Rule;
2031 | use Illuminate\Validation\Rules\File;
2032 |
2033 | Validator::validate($input, [
2034 | 'photo' => [
2035 | 'required',
2036 | File::image()
2037 | ->min(1024)
2038 | ->max(12 * 1024)
2039 | ->dimensions(Rule::dimensions()->maxWidth(1000)->maxHeight(500)),
2040 | ],
2041 | ]);
2042 |
2043 | > **Note**
2044 | > More information regarding validating image dimensions may be found in the [dimension rule documentation](#rule-dimensions).
2045 |
2046 |
2047 | #### File Types
2048 |
2049 | Even though you only need to specify the extensions when invoking the `types` method, this method actually validates 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:
2050 |
2051 | [https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types](https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types)
2052 |
2053 |
2054 | ## Validating Passwords
2055 |
2056 | To ensure that passwords have an adequate level of complexity, you may use Laravel's `Password` rule object:
2057 |
2058 | use Illuminate\Support\Facades\Validator;
2059 | use Illuminate\Validation\Rules\Password;
2060 |
2061 | $validator = Validator::make($request->all(), [
2062 | 'password' => ['required', 'confirmed', Password::min(8)],
2063 | ]);
2064 |
2065 | The `Password` rule object allows you to easily customize the password complexity requirements for your application, such as specifying that passwords require at least one letter, number, symbol, or characters with mixed casing:
2066 |
2067 | // Require at least 8 characters...
2068 | Password::min(8)
2069 |
2070 | // Require at least one letter...
2071 | Password::min(8)->letters()
2072 |
2073 | // Require at least one uppercase and one lowercase letter...
2074 | Password::min(8)->mixedCase()
2075 |
2076 | // Require at least one number...
2077 | Password::min(8)->numbers()
2078 |
2079 | // Require at least one symbol...
2080 | Password::min(8)->symbols()
2081 |
2082 | In addition, you may ensure that a password has not been compromised in a public password data breach leak using the `uncompromised` method:
2083 |
2084 | Password::min(8)->uncompromised()
2085 |
2086 | Internally, the `Password` rule object uses the [k-Anonymity](https://en.wikipedia.org/wiki/K-anonymity) model to determine if a password has been leaked via the [haveibeenpwned.com](https://haveibeenpwned.com) service without sacrificing the user's privacy or security.
2087 |
2088 | By default, if a password appears at least once in a data leak, it will be considered compromised. You can customize this threshold using the first argument of the `uncompromised` method:
2089 |
2090 | // Ensure the password appears less than 3 times in the same data leak...
2091 | Password::min(8)->uncompromised(3);
2092 |
2093 | Of course, you may chain all the methods in the examples above:
2094 |
2095 | Password::min(8)
2096 | ->letters()
2097 | ->mixedCase()
2098 | ->numbers()
2099 | ->symbols()
2100 | ->uncompromised()
2101 |
2102 |
2103 | #### Defining Default Password Rules
2104 |
2105 | You may find it convenient to specify the default validation rules for passwords in a single location of your application. You can easily accomplish this using the `Password::defaults` method, which accepts a closure. The closure given to the `defaults` method should return the default configuration of the Password rule. Typically, the `defaults` rule should be called within the `boot` method of one of your application's service providers:
2106 |
2107 | ```php
2108 | use Illuminate\Validation\Rules\Password;
2109 |
2110 | /**
2111 | * Bootstrap any application services.
2112 | */
2113 | public function boot(): void
2114 | {
2115 | Password::defaults(function () {
2116 | $rule = Password::min(8);
2117 |
2118 | return $this->app->isProduction()
2119 | ? $rule->mixedCase()->uncompromised()
2120 | : $rule;
2121 | });
2122 | }
2123 | ```
2124 |
2125 | Then, when you would like to apply the default rules to a particular password undergoing validation, you may invoke the `defaults` method with no arguments:
2126 |
2127 | 'password' => ['required', Password::defaults()],
2128 |
2129 | Occasionally, you may want to attach additional validation rules to your default password validation rules. You may use the `rules` method to accomplish this:
2130 |
2131 | use App\Rules\ZxcvbnRule;
2132 |
2133 | Password::defaults(function () {
2134 | $rule = Password::min(8)->rules([new ZxcvbnRule]);
2135 |
2136 | // ...
2137 | });
2138 |
2139 |
2140 | ## Custom Validation Rules
2141 |
2142 |
2143 | ### Using Rule Objects
2144 |
2145 | 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 rule objects. To generate a new rule object, you may use the `make:rule` Artisan command. Let's use this command to generate a rule that verifies a string is uppercase. Laravel will place the new rule in the `app/Rules` directory. If this directory does not exist, Laravel will create it when you execute the Artisan command to create your rule:
2146 |
2147 | ```shell
2148 | php artisan make:rule Uppercase
2149 | ```
2150 |
2151 | Once the rule has been created, we are ready to define its behavior. A rule object contains a single method: `validate`. This method receives the attribute name, its value, and a callback that should be invoked on failure with the validation error message:
2152 |
2153 | validate([
2178 | 'name' => ['required', 'string', new Uppercase],
2179 | ]);
2180 |
2181 | #### Translating Validation Messages
2182 |
2183 | Instead of providing a literal error message to the `$fail` closure, you may also provide a [translation string key](/docs/{{version}}/localization) and instruct Laravel to translate the error message:
2184 |
2185 | if (strtoupper($value) !== $value) {
2186 | $fail('validation.uppercase')->translate();
2187 | }
2188 |
2189 | If necessary, you may provide placeholder replacements and the preferred language as the first and second arguments to the `translate` method:
2190 |
2191 | $fail('validation.location')->translate([
2192 | 'value' => $this->value,
2193 | ], 'fr')
2194 |
2195 | #### Accessing Additional Data
2196 |
2197 | If your custom validation rule class needs to access all of the other data undergoing validation, your rule class may implement the `Illuminate\Contracts\Validation\DataAwareRule` interface. This interface requires your class to define a `setData` method. This method will automatically be invoked by Laravel (before validation proceeds) with all of the data under validation:
2198 |
2199 |
2212 | */
2213 | protected $data = [];
2214 |
2215 | // ...
2216 |
2217 | /**
2218 | * Set the data under validation.
2219 | *
2220 | * @param array $data
2221 | */
2222 | public function setData(array $data): static
2223 | {
2224 | $this->data = $data;
2225 |
2226 | return $this;
2227 | }
2228 | }
2229 |
2230 | Or, if your validation rule requires access to the validator instance performing the validation, you may implement the `ValidatorAwareRule` interface:
2231 |
2232 | validator = $validator;
2257 |
2258 | return $this;
2259 | }
2260 | }
2261 |
2262 |
2263 | ### Using Closures
2264 |
2265 | If you only need the functionality of a custom rule once throughout your application, you may use a closure instead of a rule object. The closure receives the attribute's name, the attribute's value, and a `$fail` callback that should be called if validation fails:
2266 |
2267 | use Illuminate\Support\Facades\Validator;
2268 | use Closure;
2269 |
2270 | $validator = Validator::make($request->all(), [
2271 | 'title' => [
2272 | 'required',
2273 | 'max:255',
2274 | function (string $attribute, mixed $value, Closure $fail) {
2275 | if ($value === 'foo') {
2276 | $fail("The {$attribute} is invalid.");
2277 | }
2278 | },
2279 | ],
2280 | ]);
2281 |
2282 |
2283 | ### Implicit Rules
2284 |
2285 | By default, when an attribute being validated is not present or contains an empty string, normal validation rules, including custom rules, are not run. For example, the [`unique`](#rule-unique) rule will not be run against an empty string:
2286 |
2287 | use Illuminate\Support\Facades\Validator;
2288 |
2289 | $rules = ['name' => 'unique:users,name'];
2290 |
2291 | $input = ['name' => ''];
2292 |
2293 | Validator::make($input, $rules)->passes(); // true
2294 |
2295 | For a custom rule to run even when an attribute is empty, the rule must imply that the attribute is required. To quickly generate a new implicit rule object, you may use the `make:rule` Artisan command with the `--implicit` option:
2296 |
2297 | ```shell
2298 | php artisan make:rule Uppercase --implicit
2299 | ```
2300 |
2301 | > **Warning**
2302 | > An "implicit" rule only _implies_ that the attribute is required. Whether it actually invalidates a missing or empty attribute is up to you.
2303 |
--------------------------------------------------------------------------------