+[Any Of](#rule-anyof)
[Bail](#rule-bail)
[Exclude](#rule-exclude)
[Exclude If](#rule-exclude-if)
@@ -1020,6 +1117,8 @@ Below is a list of all available validation rules and their function:
[Present With All](#rule-present-with-all)
[Prohibited](#rule-prohibited)
[Prohibited If](#rule-prohibited-if)
+[Prohibited If Accepted](#rule-prohibited-if-accepted)
+[Prohibited If Declined](#rule-prohibited-if-declined)
[Prohibited Unless](#rule-prohibited-unless)
[Prohibits](#rule-prohibits)
[Required](#rule-required)
@@ -1056,27 +1155,35 @@ The field under validation must have a valid A or AAAA record according to the `
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:
- 'start_date' => 'required|date|after:tomorrow'
+```php
+'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:
- 'finish_date' => 'required|date|after:start_date'
+```php
+'finish_date' => 'required|date|after:start_date'
+```
For convenience, date based rules may be constructed using the fluent `date` rule builder:
- use Illuminate\Validation\Rule;
+```php
+use Illuminate\Validation\Rule;
- 'start_date' => [
- 'required',
- Rule::date()->after(today()->addDays(7)),
- ],
+'start_date' => [
+ 'required',
+ Rule::date()->after(today()->addDays(7)),
+],
+```
The `afterToday` and `todayOrAfter` methods may be used to fluently express the date must be after today or or today or after, respectively:
- 'start_date' => [
- 'required',
- Rule::date()->afterToday(),
- ],
+```php
+'start_date' => [
+ 'required',
+ Rule::date()->afterToday(),
+],
+```
#### after\_or\_equal:_date_
@@ -1085,17 +1192,36 @@ The field under validation must be a value after or equal to the given date. For
For convenience, date based rules may be constructed using the fluent `date` rule builder:
- use Illuminate\Validation\Rule;
+```php
+use Illuminate\Validation\Rule;
- 'start_date' => [
- 'required',
- Rule::date()->afterOrEqual(today()->addDays(7)),
- ],
+'start_date' => [
+ 'required',
+ Rule::date()->afterOrEqual(today()->addDays(7)),
+],
+```
+
+
+#### anyOf
+
+The `Rule::anyOf` validation rule allows you to specify that the field under validation must satisfy any of the given validation rulesets. For example, the following rule will validate that the `username` field is either an email address or an alpha-numeric string (including dashes) that is at least 6 characters long:
+
+```php
+use Illuminate\Validation\Rule;
+
+'username' => [
+ 'required',
+ Rule::anyOf([
+ ['string', 'email'],
+ ['string', 'alpha_dash', 'min:6'],
+ ]),
+],
+```
#### alpha
-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=).
+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=).
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:
@@ -1106,9 +1232,9 @@ To restrict this validation rule to characters in the ASCII range (`a-z` and `A-
#### alpha_dash
-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 (`_`).
+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 (`_`).
-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:
+To restrict this validation rule to characters in the ASCII range (`a-z`, `A-Z`, and `0-9`), you may provide the `ascii` option to the validation rule:
```php
'username' => 'alpha_dash:ascii',
@@ -1117,9 +1243,9 @@ To restrict this validation rule to characters in the ASCII range (`a-z` and `A-
#### alpha_num
-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=).
+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=).
-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:
+To restrict this validation rule to characters in the ASCII range (`a-z`, `A-Z`, and `0-9`), you may provide the `ascii` option to the validation rule:
```php
'username' => 'alpha_num:ascii',
@@ -1132,19 +1258,21 @@ The field under validation must be a PHP `array`.
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:
- use Illuminate\Support\Facades\Validator;
+```php
+use Illuminate\Support\Facades\Validator;
- $input = [
- 'user' => [
- 'name' => 'Taylor Otwell',
- 'username' => 'taylorotwell',
- 'admin' => true,
- ],
- ];
+$input = [
+ 'user' => [
+ 'name' => 'Taylor Otwell',
+ 'username' => 'taylorotwell',
+ 'admin' => true,
+ ],
+];
- Validator::make($input, [
- 'user' => 'array:name,username',
- ]);
+Validator::make($input, [
+ 'user' => 'array:name,username',
+]);
+```
In general, you should always specify the array keys that are allowed to be present within your array.
@@ -1160,49 +1288,57 @@ Stop running validation rules for the field after the first validation failure.
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:
- if ($validator->stopOnFirstFailure()->fails()) {
- // ...
- }
+```php
+if ($validator->stopOnFirstFailure()->fails()) {
+ // ...
+}
+```
#### before:_date_
-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`.
+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`.
For convenience, date based rules may also be constructed using the fluent `date` rule builder:
- use Illuminate\Validation\Rule;
+```php
+use Illuminate\Validation\Rule;
- 'start_date' => [
- 'required',
- Rule::date()->before(today()->subDays(7)),
- ],
+'start_date' => [
+ 'required',
+ Rule::date()->before(today()->subDays(7)),
+],
+```
The `beforeToday` and `todayOrBefore` methods may be used to fluently express the date must be before today or or today or before, respectively:
- 'start_date' => [
- 'required',
- Rule::date()->beforeToday(),
- ],
+```php
+'start_date' => [
+ 'required',
+ Rule::date()->beforeToday(),
+],
+```
#### before\_or\_equal:_date_
-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`.
+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`.
For convenience, date based rules may also be constructed using the fluent `date` rule builder:
- use Illuminate\Validation\Rule;
+```php
+use Illuminate\Validation\Rule;
- 'start_date' => [
- 'required',
- Rule::date()->beforeOrEqual(today()->subDays(7)),
- ],
+'start_date' => [
+ 'required',
+ Rule::date()->beforeOrEqual(today()->subDays(7)),
+],
+```
#### between:_min_,_max_
-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.
+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.
#### boolean
@@ -1226,7 +1362,9 @@ The field under validation must be an array that contains all of the given param
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:
- 'password' => 'current_password:api'
+```php
+'password' => 'current_password:api'
+```
#### date
@@ -1245,23 +1383,27 @@ The field under validation must match one of the given _formats_. You should use
For convenience, date based rules may be constructed using the fluent `date` rule builder:
- use Illuminate\Validation\Rule;
+```php
+use Illuminate\Validation\Rule;
- 'start_date' => [
- 'required',
- Rule::date()->format('Y-m-d'),
- ],
+'start_date' => [
+ 'required',
+ Rule::date()->format('Y-m-d'),
+],
+```
#### decimal:_min_,_max_
The field under validation must be numeric and must contain the specified number of decimal places:
- // Must have exactly two decimal places (9.99)...
- 'price' => 'decimal:2'
+```php
+// Must have exactly two decimal places (9.99)...
+'price' => 'decimal:2'
- // Must have between 2 and 4 decimal places...
- 'price' => 'decimal:2,4'
+// Must have between 2 and 4 decimal places...
+'price' => 'decimal:2,4'
+```
#### declined
@@ -1293,43 +1435,55 @@ The integer validation must have a length between the given _min_ and _max_.
The file under validation must be an image meeting the dimension constraints as specified by the rule's parameters:
- 'avatar' => 'dimensions:min_width=100,min_height=200'
+```php
+'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 fraction like `3/2` or a float like `1.5`:
- 'avatar' => 'dimensions:ratio=3/2'
+```php
+'avatar' => 'dimensions:ratio=3/2'
+```
-Since this rule requires several arguments, it is often more convenient to use use the `Rule::dimensions` method to fluently construct the rule:
+Since this rule requires several arguments, it is often more convenient to use the `Rule::dimensions` method to fluently construct the rule:
- use Illuminate\Support\Facades\Validator;
- use Illuminate\Validation\Rule;
+```php
+use Illuminate\Support\Facades\Validator;
+use Illuminate\Validation\Rule;
- Validator::make($data, [
- 'avatar' => [
- 'required',
- Rule::dimensions()
- ->maxWidth(1000)
- ->maxHeight(500)
- ->ratio(3 / 2),
- ],
- ]);
+Validator::make($data, [
+ 'avatar' => [
+ 'required',
+ Rule::dimensions()
+ ->maxWidth(1000)
+ ->maxHeight(500)
+ ->ratio(3 / 2),
+ ],
+]);
+```
#### distinct
When validating arrays, the field under validation must not have any duplicate values:
- 'foo.*.id' => 'distinct'
+```php
+'foo.*.id' => 'distinct'
+```
Distinct uses loose variable comparisons by default. To use strict comparisons, you may add the `strict` parameter to your validation rule definition:
- 'foo.*.id' => 'distinct:strict'
+```php
+'foo.*.id' => 'distinct:strict'
+```
You may add `ignore_case` to the validation rule's arguments to make the rule ignore capitalization differences:
- 'foo.*.id' => 'distinct:ignore_case'
+```php
+'foo.*.id' => 'distinct:ignore_case'
+```
#### doesnt_start_with:_foo_,_bar_,...
@@ -1344,16 +1498,18 @@ The field under validation must not end with one of the given values.
#### email
-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:
+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:
- 'email' => 'email:rfc,dns'
+```php
+'email' => 'email:rfc,dns'
+```
The example above will apply the `RFCValidation` and `DNSCheckValidation` validations. Here's a full list of validation styles you can apply:
-- `rfc`: `RFCValidation` - Validate the email address according to RFC 5322.
-- `strict`: `NoRFCWarningsValidation` - Validate the email according to RFC 5322, rejecting trailing periods or multiple consecutive periods.
+- `rfc`: `RFCValidation` - Validate the email address according to [supported RFCs](https://github.com/egulias/EmailValidator?tab=readme-ov-file#supported-rfcs).
+- `strict`: `NoRFCWarningsValidation` - Validate the email according to [supported RFCs](https://github.com/egulias/EmailValidator?tab=readme-ov-file#supported-rfcs), failing when warnings are found (e.g. trailing periods and multiple consecutive periods).
- `dns`: `DNSCheckValidation` - Ensure the email address's domain has a valid MX record.
- `spoof`: `SpoofCheckValidation` - Ensure the email address does not contain homograph or deceptive Unicode characters.
- `filter`: `FilterEmailValidation` - Ensure the email address is valid according to PHP's `filter_var` function.
@@ -1377,7 +1533,7 @@ $request->validate([
]);
```
-> [!WARNING]
+> [!WARNING]
> The `dns` and `spoof` validators require the PHP `intl` extension.
@@ -1390,20 +1546,24 @@ The field under validation must end with one of the given values.
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. When validating primitive values, a backed Enum should be provided to the `Enum` rule:
- use App\Enums\ServerStatus;
- use Illuminate\Validation\Rule;
+```php
+use App\Enums\ServerStatus;
+use Illuminate\Validation\Rule;
- $request->validate([
- 'status' => [Rule::enum(ServerStatus::class)],
- ]);
+$request->validate([
+ 'status' => [Rule::enum(ServerStatus::class)],
+]);
+```
The `Enum` rule's `only` and `except` methods may be used to limit which enum cases should be considered valid:
- Rule::enum(ServerStatus::class)
- ->only([ServerStatus::Pending, ServerStatus::Active]);
+```php
+Rule::enum(ServerStatus::class)
+ ->only([ServerStatus::Pending, ServerStatus::Active]);
- Rule::enum(ServerStatus::class)
- ->except([ServerStatus::Pending, ServerStatus::Active]);
+Rule::enum(ServerStatus::class)
+ ->except([ServerStatus::Pending, ServerStatus::Active]);
+```
The `when` method may be used to conditionally modify the `Enum` rule:
@@ -1431,16 +1591,18 @@ The field under validation will be excluded from the request data returned by th
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:
- use Illuminate\Support\Facades\Validator;
- use Illuminate\Validation\Rule;
+```php
+use Illuminate\Support\Facades\Validator;
+use Illuminate\Validation\Rule;
- Validator::make($request->all(), [
- 'role_id' => Rule::excludeIf($request->user()->is_admin),
- ]);
+Validator::make($request->all(), [
+ 'role_id' => Rule::excludeIf($request->user()->is_admin),
+]);
- Validator::make($request->all(), [
- 'role_id' => Rule::excludeIf(fn () => $request->user()->is_admin),
- ]);
+Validator::make($request->all(), [
+ 'role_id' => Rule::excludeIf(fn () => $request->user()->is_admin),
+]);
+```
#### exclude_unless:_anotherfield_,_value_
@@ -1465,7 +1627,9 @@ The field under validation must exist in a given database table.
#### Basic Usage of Exists Rule
- 'state' => 'exists:states'
+```php
+'state' => 'exists:states'
+```
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.
@@ -1474,44 +1638,56 @@ If the `column` option is not specified, the field name will be used. So, in thi
You may explicitly specify the database column name that should be used by the validation rule by placing it after the database table name:
- 'state' => 'exists:states,abbreviation'
+```php
+'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:
- 'email' => 'exists:connection.staff,email'
+```php
+'email' => 'exists:connection.staff,email'
+```
Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name:
- 'user_id' => 'exists:App\Models\User,id'
+```php
+'user_id' => 'exists:App\Models\User,id'
+```
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:
- use Illuminate\Database\Query\Builder;
- use Illuminate\Support\Facades\Validator;
- use Illuminate\Validation\Rule;
+```php
+use Illuminate\Database\Query\Builder;
+use Illuminate\Support\Facades\Validator;
+use Illuminate\Validation\Rule;
- Validator::make($data, [
- 'email' => [
- 'required',
- Rule::exists('staff')->where(function (Builder $query) {
- $query->where('account_id', 1);
- }),
- ],
- ]);
+Validator::make($data, [
+ 'email' => [
+ 'required',
+ Rule::exists('staff')->where(function (Builder $query) {
+ $query->where('account_id', 1);
+ }),
+ ],
+]);
+```
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:
- 'state' => Rule::exists('states', 'abbreviation'),
+```php
+'state' => Rule::exists('states', 'abbreviation'),
+```
#### extensions:_foo_,_bar_,...
The file under validation must have a user-assigned extension corresponding to one of the listed extensions:
- 'photo' => ['required', 'extensions:jpg,png'],
+```php
+'photo' => ['required', 'extensions:jpg,png'],
+```
-> [!WARNING]
-> You should never rely on validating a file by its user-assigned extension alone. This rule should typically always be used in combination with the [`mimes`](#rule-mimes) or [`mimetypes`](#rule-mimetypes) rules.
+> [!WARNING]
+> You should never rely on validating a file by its user-assigned extension alone. This rule should typically always be used in combination with the [mimes](#rule-mimes) or [mimetypes](#rule-mimetypes) rules.
#### file
@@ -1526,12 +1702,12 @@ The field under validation must not be empty when it is present.
#### gt:_field_
-The field under validation must be greater than the given _field_ or _value_. 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.
+The field under validation must be greater than the given _field_ or _value_. 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.
#### gte:_field_
-The field under validation must be greater than or equal to the given _field_ or _value_. 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.
+The field under validation must be greater than or equal to the given _field_ or _value_. 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.
#### hex_color
@@ -1541,39 +1717,46 @@ The field under validation must contain a valid color value in [hexadecimal](htt
#### image
-The file under validation must be an image (jpg, jpeg, png, bmp, gif, svg, or webp).
+The file under validation must be an image (jpg, jpeg, png, bmp, gif, or webp).
+
+> [!WARNING]
+> By default, the image rule does not allow SVG files due to the possibility of XSS vulnerabilities. If you need to allow SVG files, you may provide the `allow_svg` directive to the `image` rule (`image:allow_svg`).
#### in:_foo_,_bar_,...
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:
- use Illuminate\Support\Facades\Validator;
- use Illuminate\Validation\Rule;
+```php
+use Illuminate\Support\Facades\Validator;
+use Illuminate\Validation\Rule;
- Validator::make($data, [
- 'zones' => [
- 'required',
- Rule::in(['first-zone', 'second-zone']),
- ],
- ]);
+Validator::make($data, [
+ 'zones' => [
+ 'required',
+ Rule::in(['first-zone', 'second-zone']),
+ ],
+]);
+```
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:
- use Illuminate\Support\Facades\Validator;
- use Illuminate\Validation\Rule;
+```php
+use Illuminate\Support\Facades\Validator;
+use Illuminate\Validation\Rule;
- $input = [
- 'airports' => ['NYC', 'LAS'],
- ];
+$input = [
+ 'airports' => ['NYC', 'LAS'],
+];
- Validator::make($input, [
- 'airports' => [
- 'required',
- 'array',
- ],
- 'airports.*' => Rule::in(['NYC', 'LIT']),
- ]);
+Validator::make($input, [
+ 'airports' => [
+ 'required',
+ 'array',
+ ],
+ 'airports.*' => Rule::in(['NYC', 'LIT']),
+]);
+```
#### in_array:_anotherfield_.*
@@ -1585,7 +1768,7 @@ The field under validation must exist in _anotherfield_'s values.
The field under validation must be an integer.
-> [!WARNING]
+> [!WARNING]
> 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).
@@ -1611,12 +1794,12 @@ The field under validation must be a valid JSON string.
#### lt:_field_
-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.
+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.
#### lte:_field_
-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.
+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.
#### lowercase
@@ -1636,7 +1819,7 @@ The field under validation must be a MAC address.
#### max:_value_
-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.
+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.
#### max_digits:_value_
@@ -1648,7 +1831,9 @@ The integer under validation must have a maximum length of _value_.
The file under validation must match one of the given MIME types:
- 'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime'
+```php
+'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's provided MIME type.
@@ -1657,7 +1842,9 @@ To determine the MIME type of the uploaded file, the file's contents will be rea
The file under validation must have a MIME type corresponding to one of the listed extensions:
- 'photo' => 'mimes:jpg,bmp,png'
+```php
+'photo' => 'mimes:jpg,bmp,png'
+```
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:
@@ -1666,12 +1853,12 @@ Even though you only need to specify the extensions, this rule actually validate
#### MIME Types and Extensions
-This validation rule does not verify agreement between the MIME type and the extension the user assigned to the file. For example, the `mimes:png` validation rule would consider a file containing valid PNG content to be a valid PNG image, even if the file is named `photo.txt`. If you would like to validate the user-assigned extension of the file, you may use the [`extensions`](#rule-extensions) rule.
+This validation rule does not verify agreement between the MIME type and the extension the user assigned to the file. For example, the `mimes:png` validation rule would consider a file containing valid PNG content to be a valid PNG image, even if the file is named `photo.txt`. If you would like to validate the user-assigned extension of the file, you may use the [extensions](#rule-extensions) rule.
#### min:_value_
-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.
+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.
#### min_digits:_value_
@@ -1713,14 +1900,16 @@ The field under validation must not be present _only if_ all of the other specif
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:
- use Illuminate\Validation\Rule;
+```php
+use Illuminate\Validation\Rule;
- Validator::make($data, [
- 'toppings' => [
- 'required',
- Rule::notIn(['sprinkles', 'cherries']),
- ],
- ]);
+Validator::make($data, [
+ 'toppings' => [
+ 'required',
+ Rule::notIn(['sprinkles', 'cherries']),
+ ],
+]);
+```
#### not_regex:_pattern_
@@ -1729,7 +1918,7 @@ The field under validation must not match the given regular expression.
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'`.
-> [!WARNING]
+> [!WARNING]
> 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.
@@ -1797,16 +1986,27 @@ The field under validation must be missing or empty if the _anotherfield_ field
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:
- use Illuminate\Support\Facades\Validator;
- use Illuminate\Validation\Rule;
+```php
+use Illuminate\Support\Facades\Validator;
+use Illuminate\Validation\Rule;
- Validator::make($request->all(), [
- 'role_id' => Rule::prohibitedIf($request->user()->is_admin),
- ]);
+Validator::make($request->all(), [
+ 'role_id' => Rule::prohibitedIf($request->user()->is_admin),
+]);
- Validator::make($request->all(), [
- 'role_id' => Rule::prohibitedIf(fn () => $request->user()->is_admin),
- ]);
+Validator::make($request->all(), [
+ 'role_id' => Rule::prohibitedIf(fn () => $request->user()->is_admin),
+]);
+```
+
+#### prohibited_if_accepted:_anotherfield_,...
+
+The field under validation must be missing or empty if the _anotherfield_ field is equal to `"yes"`, `"on"`, `1`, `"1"`, `true`, or `"true"`.
+
+
+#### prohibited_if_declined:_anotherfield_,...
+
+The field under validation must be missing or empty if the _anotherfield_ field is equal to `"no"`, `"off"`, `0`, `"0"`, `false`, or `"false"`.
#### prohibited_unless:_anotherfield_,_value_,...
@@ -1843,7 +2043,7 @@ The field under validation must match the given regular expression.
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'`.
-> [!WARNING]
+> [!WARNING]
> 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.
@@ -1867,16 +2067,18 @@ The field under validation must be present and not empty if the _anotherfield_ f
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:
- use Illuminate\Support\Facades\Validator;
- use Illuminate\Validation\Rule;
+```php
+use Illuminate\Support\Facades\Validator;
+use Illuminate\Validation\Rule;
- Validator::make($request->all(), [
- 'role_id' => Rule::requiredIf($request->user()->is_admin),
- ]);
+Validator::make($request->all(), [
+ 'role_id' => Rule::requiredIf($request->user()->is_admin),
+]);
- Validator::make($request->all(), [
- 'role_id' => Rule::requiredIf(fn () => $request->user()->is_admin),
- ]);
+Validator::make($request->all(), [
+ 'role_id' => Rule::requiredIf(fn () => $request->user()->is_admin),
+]);
+```
#### required_if_accepted:_anotherfield_,...
@@ -1928,17 +2130,19 @@ The given _field_ must match the field under validation.
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:
- // Validate that a string is exactly 12 characters long...
- 'title' => 'size:12';
+```php
+// Validate that a string is exactly 12 characters long...
+'title' => 'size:12';
- // Validate that a provided integer equals 10...
- 'seats' => 'integer|size:10';
+// Validate that a provided integer equals 10...
+'seats' => 'integer|size:10';
- // Validate that an array has exactly 5 elements...
- 'tags' => 'array|size:5';
+// Validate that an array has exactly 5 elements...
+'tags' => 'array|size:5';
- // Validate that an uploaded file is exactly 512 kilobytes...
- 'image' => 'file|size:512';
+// Validate that an uploaded file is exactly 512 kilobytes...
+'image' => 'file|size:512';
+```
#### starts_with:_foo_,_bar_,...
@@ -1957,11 +2161,13 @@ The field under validation must be a valid timezone identifier according to the
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:
- 'timezone' => 'required|timezone:all';
+```php
+'timezone' => 'required|timezone:all';
- 'timezone' => 'required|timezone:Africa';
+'timezone' => 'required|timezone:Africa';
- 'timezone' => 'required|timezone:per_country,US';
+'timezone' => 'required|timezone:per_country,US';
+```
#### unique:_table_,_column_
@@ -1972,17 +2178,23 @@ The field under validation must not exist within the given database table.
Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name:
- 'email' => 'unique:App\Models\User,email_address'
+```php
+'email' => 'unique:App\Models\User,email_address'
+```
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.
- 'email' => 'unique:users,email_address'
+```php
+'email' => 'unique:users,email_address'
+```
**Specifying a Custom Database Connection**
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:
- 'email' => 'unique:connection.users,email_address'
+```php
+'email' => 'unique:connection.users,email_address'
+```
**Forcing a Unique Rule to Ignore a Given ID:**
@@ -1990,46 +2202,60 @@ Sometimes, you may wish to ignore a given ID during unique validation. For examp
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:
- use Illuminate\Support\Facades\Validator;
- use Illuminate\Validation\Rule;
+```php
+use Illuminate\Support\Facades\Validator;
+use Illuminate\Validation\Rule;
- Validator::make($data, [
- 'email' => [
- 'required',
- Rule::unique('users')->ignore($user->id),
- ],
- ]);
+Validator::make($data, [
+ 'email' => [
+ 'required',
+ Rule::unique('users')->ignore($user->id),
+ ],
+]);
+```
-> [!WARNING]
+> [!WARNING]
> 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.
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:
- Rule::unique('users')->ignore($user)
+```php
+Rule::unique('users')->ignore($user)
+```
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:
- Rule::unique('users')->ignore($user->id, 'user_id')
+```php
+Rule::unique('users')->ignore($user->id, 'user_id')
+```
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:
- Rule::unique('users', 'email_address')->ignore($user->id)
+```php
+Rule::unique('users', 'email_address')->ignore($user->id)
+```
**Adding Additional Where Clauses:**
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`:
- 'email' => Rule::unique('users')->where(fn (Builder $query) => $query->where('account_id', 1))
+```php
+'email' => Rule::unique('users')->where(fn (Builder $query) => $query->where('account_id', 1))
+```
**Ignoring Soft Deleteded Records in Unique Checks:**
By default, the unique rule includes soft deleted records when determining uniqueness. To exclude soft deleted records from the uniqueness check, you may invoke the `withoutTrashed` method:
- Rule::unique('users')->withoutTrashed();
+```php
+Rule::unique('users')->withoutTrashed();
+```
If your model uses a column name other than `deleted_at` for soft deleted records, you may provide the column name when invoking the `withoutTrashed` method:
- Rule::unique('users')->withoutTrashed('was_deleted_at');
+```php
+Rule::unique('users')->withoutTrashed('was_deleted_at');
+```
#### uppercase
@@ -2059,6 +2285,12 @@ The field under validation must be a valid [Universally Unique Lexicographically
The field under validation must be a valid RFC 9562 (version 1, 3, 4, 5, 6, 7, or 8) universally unique identifier (UUID).
+You may also validate that the given UUID matches a UUID specification by version:
+
+```php
+'uuid' => 'uuid:4'
+```
+
## Conditionally Adding Rules
@@ -2067,34 +2299,40 @@ The field under validation must be a valid RFC 9562 (version 1, 3, 4, 5, 6, 7, o
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`:
- use Illuminate\Support\Facades\Validator;
+```php
+use Illuminate\Support\Facades\Validator;
- $validator = Validator::make($data, [
- 'has_appointment' => 'required|boolean',
- 'appointment_date' => 'exclude_if:has_appointment,false|required|date',
- 'doctor_name' => 'exclude_if:has_appointment,false|required|string',
- ]);
+$validator = Validator::make($data, [
+ 'has_appointment' => 'required|boolean',
+ 'appointment_date' => 'exclude_if:has_appointment,false|required|date',
+ 'doctor_name' => 'exclude_if:has_appointment,false|required|string',
+]);
+```
Alternatively, you may use the `exclude_unless` rule to not validate a given field unless another field has a given value:
- $validator = Validator::make($data, [
- 'has_appointment' => 'required|boolean',
- 'appointment_date' => 'exclude_unless:has_appointment,true|required|date',
- 'doctor_name' => 'exclude_unless:has_appointment,true|required|string',
- ]);
+```php
+$validator = Validator::make($data, [
+ 'has_appointment' => 'required|boolean',
+ 'appointment_date' => 'exclude_unless:has_appointment,true|required|date',
+ 'doctor_name' => 'exclude_unless:has_appointment,true|required|string',
+]);
+```
#### Validating When Present
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:
- $validator = Validator::make($data, [
- 'email' => 'sometimes|required|email',
- ]);
+```php
+$validator = Validator::make($data, [
+ 'email' => 'sometimes|required|email',
+]);
+```
In the example above, the `email` field will only be validated if it is present in the `$data` array.
-> [!NOTE]
+> [!NOTE]
> 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).
@@ -2102,28 +2340,34 @@ In the example above, the `email` field will only be validated if it is present
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:
- use Illuminate\Support\Facades\Validator;
+```php
+use Illuminate\Support\Facades\Validator;
- $validator = Validator::make($request->all(), [
- 'email' => 'required|email',
- 'games' => 'required|numeric',
- ]);
+$validator = Validator::make($request->all(), [
+ 'email' => 'required|email',
+ 'games' => 'required|integer|min:0',
+]);
+```
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.
- use Illuminate\Support\Fluent;
+```php
+use Illuminate\Support\Fluent;
- $validator->sometimes('reason', 'required|max:500', function (Fluent $input) {
- return $input->games >= 100;
- });
+$validator->sometimes('reason', 'required|max:500', function (Fluent $input) {
+ return $input->games >= 100;
+});
+```
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:
- $validator->sometimes(['reason', 'cost'], 'required', function (Fluent $input) {
- return $input->games >= 100;
- });
+```php
+$validator->sometimes(['reason', 'cost'], 'required', function (Fluent $input) {
+ return $input->games >= 100;
+});
+```
-> [!NOTE]
+> [!NOTE]
> 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.
@@ -2131,47 +2375,51 @@ The first argument passed to the `sometimes` method is the name of the field we
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:
- $input = [
- 'channels' => [
- [
- 'type' => 'email',
- 'address' => 'abigail@example.com',
- ],
- [
- 'type' => 'url',
- 'address' => 'https://example.com',
- ],
+```php
+$input = [
+ 'channels' => [
+ [
+ 'type' => 'email',
+ 'address' => 'abigail@example.com',
],
- ];
+ [
+ 'type' => 'url',
+ 'address' => 'https://example.com',
+ ],
+ ],
+];
- $validator->sometimes('channels.*.address', 'email', function (Fluent $input, Fluent $item) {
- return $item->type === 'email';
- });
+$validator->sometimes('channels.*.address', 'email', function (Fluent $input, Fluent $item) {
+ return $item->type === 'email';
+});
- $validator->sometimes('channels.*.address', 'url', function (Fluent $input, Fluent $item) {
- return $item->type !== 'email';
- });
+$validator->sometimes('channels.*.address', 'url', function (Fluent $input, Fluent $item) {
+ return $item->type !== 'email';
+});
+```
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.
## Validating Arrays
-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:
+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:
- use Illuminate\Support\Facades\Validator;
+```php
+use Illuminate\Support\Facades\Validator;
- $input = [
- 'user' => [
- 'name' => 'Taylor Otwell',
- 'username' => 'taylorotwell',
- 'admin' => true,
- ],
- ];
+$input = [
+ 'user' => [
+ 'name' => 'Taylor Otwell',
+ 'username' => 'taylorotwell',
+ 'admin' => true,
+ ],
+];
- Validator::make($input, [
- 'user' => 'array:name,username',
- ]);
+Validator::make($input, [
+ 'user' => 'array:name,username',
+]);
+```
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.
@@ -2180,93 +2428,107 @@ In general, you should always specify the array keys that are allowed to be pres
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:
- use Illuminate\Support\Facades\Validator;
+```php
+use Illuminate\Support\Facades\Validator;
- $validator = Validator::make($request->all(), [
- 'photos.profile' => 'required|image',
- ]);
+$validator = Validator::make($request->all(), [
+ 'photos.profile' => 'required|image',
+]);
+```
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:
- $validator = Validator::make($request->all(), [
- 'person.*.email' => 'email|unique:users',
- 'person.*.first_name' => 'required_with:person.*.last_name',
- ]);
+```php
+$validator = Validator::make($request->all(), [
+ 'person.*.email' => 'email|unique:users',
+ 'person.*.first_name' => 'required_with:person.*.last_name',
+]);
+```
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:
- 'custom' => [
- 'person.*.email' => [
- 'unique' => 'Each person must have a unique email address',
- ]
- ],
+```php
+'custom' => [
+ 'person.*.email' => [
+ 'unique' => 'Each person must have a unique email address',
+ ]
+],
+```
#### Accessing Nested Array Data
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:
- use App\Rules\HasPermission;
- use Illuminate\Support\Facades\Validator;
- use Illuminate\Validation\Rule;
+```php
+use App\Rules\HasPermission;
+use Illuminate\Support\Facades\Validator;
+use Illuminate\Validation\Rule;
- $validator = Validator::make($request->all(), [
- 'companies.*.id' => Rule::forEach(function (string|null $value, string $attribute) {
- return [
- Rule::exists(Company::class, 'id'),
- new HasPermission('manage-company', $value),
- ];
- }),
- ]);
+$validator = Validator::make($request->all(), [
+ 'companies.*.id' => Rule::forEach(function (string|null $value, string $attribute) {
+ return [
+ Rule::exists(Company::class, 'id'),
+ new HasPermission('manage-company', $value),
+ ];
+ }),
+]);
+```
### Error Message Indexes and Positions
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):
- use Illuminate\Support\Facades\Validator;
-
- $input = [
- 'photos' => [
- [
- 'name' => 'BeachVacation.jpg',
- 'description' => 'A photo of my beach vacation!',
- ],
- [
- 'name' => 'GrandCanyon.jpg',
- 'description' => '',
- ],
+```php
+use Illuminate\Support\Facades\Validator;
+
+$input = [
+ 'photos' => [
+ [
+ 'name' => 'BeachVacation.jpg',
+ 'description' => 'A photo of my beach vacation!',
],
- ];
+ [
+ 'name' => 'GrandCanyon.jpg',
+ 'description' => '',
+ ],
+ ],
+];
- Validator::validate($input, [
- 'photos.*.description' => 'required',
- ], [
- 'photos.*.description.required' => 'Please describe photo #:position.',
- ]);
+Validator::validate($input, [
+ 'photos.*.description' => 'required',
+], [
+ 'photos.*.description.required' => 'Please describe photo #:position.',
+]);
+```
Given the example above, validation will fail and the user will be presented with the following error of _"Please describe photo #2."_
If necessary, you may reference more deeply nested indexes and positions via `second-index`, `second-position`, `third-index`, `third-position`, etc.
- 'photos.*.attributes.*.string' => 'Invalid attribute for photo #:second-position.',
+```php
+'photos.*.attributes.*.string' => 'Invalid attribute for photo #:second-position.',
+```
## Validating Files
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:
- use Illuminate\Support\Facades\Validator;
- use Illuminate\Validation\Rules\File;
+```php
+use Illuminate\Support\Facades\Validator;
+use Illuminate\Validation\Rules\File;
- Validator::validate($input, [
- 'attachment' => [
- 'required',
- File::types(['mp3', 'wav'])
- ->min(1024)
- ->max(12 * 1024),
- ],
- ]);
+Validator::validate($input, [
+ 'attachment' => [
+ 'required',
+ File::types(['mp3', 'wav'])
+ ->min(1024)
+ ->max(12 * 1024),
+ ],
+]);
+```
#### Validating File Types
@@ -2289,7 +2551,9 @@ File::types(['mp3', 'wav'])
#### Validating Image Files
-To validate that uploaded files are images, you can use the `File` rule's `image` constructor method. The `File::image()` rule ensures that the file under validation is an image (jpg, jpeg, png, bmp, gif, svg, or webp):
+If your application accepts images uploaded by your users, you may use the `File` rule's `image` constructor method to ensure that the file under validation is an image (jpg, jpeg, png, bmp, gif, or webp).
+
+In addition, the `dimensions` rule may be used to limit the dimensions of the image:
```php
use Illuminate\Support\Facades\Validator;
@@ -2299,11 +2563,20 @@ use Illuminate\Validation\Rules\File;
Validator::validate($input, [
'photo' => [
'required',
- File::image(),
+ File::image()
+ ->min(1024)
+ ->max(12 * 1024)
+ ->dimensions(Rule::dimensions()->maxWidth(1000)->maxHeight(500)),
],
]);
```
+> [!NOTE]
+> More information regarding validating image dimensions may be found in the [dimension rule documentation](#rule-dimensions).
+
+> [!WARNING]
+> By default, the `image` rule does not allow SVG files due to the possibility of XSS vulnerabilities. If you need to allow SVG files, you may pass `allowSvg: true` to the `image` rule: `File::image(allowSvg: true)`.
+
#### Validating Image Dimensions
@@ -2320,7 +2593,7 @@ File::image()->dimensions(
)
```
-> [!NOTE]
+> [!NOTE]
> More information regarding validating image dimensions may be found in the [dimension rule documentation](#rule-dimensions).
@@ -2328,49 +2601,59 @@ File::image()->dimensions(
To ensure that passwords have an adequate level of complexity, you may use Laravel's `Password` rule object:
- use Illuminate\Support\Facades\Validator;
- use Illuminate\Validation\Rules\Password;
+```php
+use Illuminate\Support\Facades\Validator;
+use Illuminate\Validation\Rules\Password;
- $validator = Validator::make($request->all(), [
- 'password' => ['required', 'confirmed', Password::min(8)],
- ]);
+$validator = Validator::make($request->all(), [
+ 'password' => ['required', 'confirmed', Password::min(8)],
+]);
+```
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:
- // Require at least 8 characters...
- Password::min(8)
+```php
+// Require at least 8 characters...
+Password::min(8)
- // Require at least one letter...
- Password::min(8)->letters()
+// Require at least one letter...
+Password::min(8)->letters()
- // Require at least one uppercase and one lowercase letter...
- Password::min(8)->mixedCase()
+// Require at least one uppercase and one lowercase letter...
+Password::min(8)->mixedCase()
- // Require at least one number...
- Password::min(8)->numbers()
+// Require at least one number...
+Password::min(8)->numbers()
- // Require at least one symbol...
- Password::min(8)->symbols()
+// Require at least one symbol...
+Password::min(8)->symbols()
+```
In addition, you may ensure that a password has not been compromised in a public password data breach leak using the `uncompromised` method:
- Password::min(8)->uncompromised()
+```php
+Password::min(8)->uncompromised()
+```
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.
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:
- // Ensure the password appears less than 3 times in the same data leak...
- Password::min(8)->uncompromised(3);
+```php
+// Ensure the password appears less than 3 times in the same data leak...
+Password::min(8)->uncompromised(3);
+```
Of course, you may chain all the methods in the examples above:
- Password::min(8)
- ->letters()
- ->mixedCase()
- ->numbers()
- ->symbols()
- ->uncompromised()
+```php
+Password::min(8)
+ ->letters()
+ ->mixedCase()
+ ->numbers()
+ ->symbols()
+ ->uncompromised()
+```
#### Defining Default Password Rules
@@ -2397,17 +2680,21 @@ public function boot(): void
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:
- 'password' => ['required', Password::defaults()],
+```php
+'password' => ['required', Password::defaults()],
+```
Occasionally, you may want to attach additional validation rules to your default password validation rules. You may use the `rules` method to accomplish this:
- use App\Rules\ZxcvbnRule;
+```php
+use App\Rules\ZxcvbnRule;
- Password::defaults(function () {
- $rule = Password::min(8)->rules([new ZxcvbnRule]);
+Password::defaults(function () {
+ $rule = Password::min(8)->rules([new ZxcvbnRule]);
- // ...
- });
+ // ...
+});
+```
## Custom Validation Rules
@@ -2423,147 +2710,163 @@ php artisan make:rule Uppercase
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:
- validate([
- 'name' => ['required', 'string', new Uppercase],
- ]);
+$request->validate([
+ 'name' => ['required', 'string', new Uppercase],
+]);
+```
#### Translating Validation Messages
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:
- if (strtoupper($value) !== $value) {
- $fail('validation.uppercase')->translate();
- }
+```php
+if (strtoupper($value) !== $value) {
+ $fail('validation.uppercase')->translate();
+}
+```
If necessary, you may provide placeholder replacements and the preferred language as the first and second arguments to the `translate` method:
- $fail('validation.location')->translate([
- 'value' => $this->value,
- ], 'fr')
+```php
+$fail('validation.location')->translate([
+ 'value' => $this->value,
+], 'fr');
+```
#### Accessing Additional Data
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:
-
- */
- protected $data = [];
+class Uppercase implements DataAwareRule, ValidationRule
+{
+ /**
+ * All of the data under validation.
+ *
+ * @var array
+ */
+ protected $data = [];
- // ...
+ // ...
- /**
- * Set the data under validation.
- *
- * @param array $data
- */
- public function setData(array $data): static
- {
- $this->data = $data;
+ /**
+ * Set the data under validation.
+ *
+ * @param array $data
+ */
+ public function setData(array $data): static
+ {
+ $this->data = $data;
- return $this;
- }
+ return $this;
}
+}
+```
Or, if your validation rule requires access to the validator instance performing the validation, you may implement the `ValidatorAwareRule` interface:
- validator = $validator;
+ /**
+ * Set the current validator.
+ */
+ public function setValidator(Validator $validator): static
+ {
+ $this->validator = $validator;
- return $this;
- }
+ return $this;
}
+}
+```
### Using Closures
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:
- use Illuminate\Support\Facades\Validator;
- use Closure;
-
- $validator = Validator::make($request->all(), [
- 'title' => [
- 'required',
- 'max:255',
- function (string $attribute, mixed $value, Closure $fail) {
- if ($value === 'foo') {
- $fail("The {$attribute} is invalid.");
- }
- },
- ],
- ]);
+```php
+use Illuminate\Support\Facades\Validator;
+use Closure;
+
+$validator = Validator::make($request->all(), [
+ 'title' => [
+ 'required',
+ 'max:255',
+ function (string $attribute, mixed $value, Closure $fail) {
+ if ($value === 'foo') {
+ $fail("The {$attribute} is invalid.");
+ }
+ },
+ ],
+]);
+```
### Implicit Rules
-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:
+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:
- use Illuminate\Support\Facades\Validator;
+```php
+use Illuminate\Support\Facades\Validator;
- $rules = ['name' => 'unique:users,name'];
+$rules = ['name' => 'unique:users,name'];
- $input = ['name' => ''];
+$input = ['name' => ''];
- Validator::make($input, $rules)->passes(); // true
+Validator::make($input, $rules)->passes(); // true
+```
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:
@@ -2571,5 +2874,5 @@ For a custom rule to run even when an attribute is empty, the rule must imply th
php artisan make:rule Uppercase --implicit
```
-> [!WARNING]
+> [!WARNING]
> An "implicit" rule only _implies_ that the attribute is required. Whether it actually invalidates a missing or empty attribute is up to you.
diff --git a/verification.md b/verification.md
index d6c0a75249..b8d05eebbd 100644
--- a/verification.md
+++ b/verification.md
@@ -16,7 +16,7 @@
Many web applications require users to verify their email addresses before using the application. Rather than forcing you to re-implement this feature by hand for each application you create, Laravel provides convenient built-in services for sending and verifying email verification requests.
-> [!NOTE]
+> [!NOTE]
> Want to get started fast? Install one of the [Laravel application starter kits](/docs/{{version}}/starter-kits) in a fresh Laravel application. The starter kits will take care of scaffolding your entire authentication system, including email verification support.
@@ -24,28 +24,32 @@ Many web applications require users to verify their email addresses before using
Before getting started, verify that your `App\Models\User` model implements the `Illuminate\Contracts\Auth\MustVerifyEmail` contract:
-
### Database Preparation
@@ -66,13 +70,15 @@ Third, a route will be needed to resend a verification link if the user accident
As mentioned previously, a route should be defined that will return a view instructing the user to click the email verification link that was emailed to them by Laravel after registration. This view will be displayed to users when they try to access other parts of the application without verifying their email address first. Remember, the link is automatically emailed to the user as long as your `App\Models\User` model implements the `MustVerifyEmail` interface:
- Route::get('/email/verify', function () {
- return view('auth.verify-email');
- })->middleware('auth')->name('verification.notice');
+```php
+Route::get('/email/verify', function () {
+ return view('auth.verify-email');
+})->middleware('auth')->name('verification.notice');
+```
The route that returns the email verification notice should be named `verification.notice`. It is important that the route is assigned this exact name since the `verified` middleware [included with Laravel](#protecting-routes) will automatically redirect to this route name if a user has not verified their email address.
-> [!NOTE]
+> [!NOTE]
> When manually implementing email verification, you are required to define the contents of the verification notice view yourself. If you would like scaffolding that includes all necessary authentication and verification views, check out the [Laravel application starter kits](/docs/{{version}}/starter-kits).
@@ -80,13 +86,15 @@ The route that returns the email verification notice should be named `verificati
Next, we need to define a route that will handle requests generated when the user clicks the email verification link that was emailed to them. This route should be named `verification.verify` and be assigned the `auth` and `signed` middlewares:
- use Illuminate\Foundation\Auth\EmailVerificationRequest;
+```php
+use Illuminate\Foundation\Auth\EmailVerificationRequest;
- Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
- $request->fulfill();
+Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
+ $request->fulfill();
- return redirect('/home');
- })->middleware(['auth', 'signed'])->name('verification.verify');
+ return redirect('/home');
+})->middleware(['auth', 'signed'])->name('verification.verify');
+```
Before moving on, let's take a closer look at this route. First, you'll notice we are using an `EmailVerificationRequest` request type instead of the typical `Illuminate\Http\Request` instance. The `EmailVerificationRequest` is a [form request](/docs/{{version}}/validation#form-request-validation) that is included with Laravel. This request will automatically take care of validating the request's `id` and `hash` parameters.
@@ -97,22 +105,26 @@ Next, we can proceed directly to calling the `fulfill` method on the request. Th
Sometimes a user may misplace or accidentally delete the email address verification email. To accommodate this, you may wish to define a route to allow the user to request that the verification email be resent. You may then make a request to this route by placing a simple form submission button within your [verification notice view](#the-email-verification-notice):
- use Illuminate\Http\Request;
+```php
+use Illuminate\Http\Request;
- Route::post('/email/verification-notification', function (Request $request) {
- $request->user()->sendEmailVerificationNotification();
+Route::post('/email/verification-notification', function (Request $request) {
+ $request->user()->sendEmailVerificationNotification();
- return back()->with('message', 'Verification link sent!');
- })->middleware(['auth', 'throttle:6,1'])->name('verification.send');
+ return back()->with('message', 'Verification link sent!');
+})->middleware(['auth', 'throttle:6,1'])->name('verification.send');
+```
### Protecting Routes
[Route middleware](/docs/{{version}}/middleware) may be used to only allow verified users to access a given route. Laravel includes a `verified` [middleware alias](/docs/{{version}}/middleware#middleware-aliases), which is an alias for the `Illuminate\Auth\Middleware\EnsureEmailIsVerified` middleware class. Since this alias is already automatically registered by Laravel, all you need to do is attach the `verified` middleware to a route definition. Typically, this middleware is paired with the `auth` middleware:
- Route::get('/profile', function () {
- // Only verified users may access this route...
- })->middleware(['auth', 'verified']);
+```php
+Route::get('/profile', function () {
+ // Only verified users may access this route...
+})->middleware(['auth', 'verified']);
+```
If an unverified user attempts to access a route that has been assigned this middleware, they will automatically be redirected to the `verification.notice` [named route](/docs/{{version}}/routing#named-routes).
@@ -126,25 +138,27 @@ Although the default email verification notification should satisfy the requirem
To get started, pass a closure to the `toMailUsing` method provided by the `Illuminate\Auth\Notifications\VerifyEmail` notification. The closure will receive the notifiable model instance that is receiving the notification as well as the signed email verification URL that the user must visit to verify their email address. The closure should return an instance of `Illuminate\Notifications\Messages\MailMessage`. Typically, you should call the `toMailUsing` method from the `boot` method of your application's `AppServiceProvider` class:
- use Illuminate\Auth\Notifications\VerifyEmail;
- use Illuminate\Notifications\Messages\MailMessage;
-
- /**
- * Bootstrap any application services.
- */
- public function boot(): void
- {
- // ...
-
- VerifyEmail::toMailUsing(function (object $notifiable, string $url) {
- return (new MailMessage)
- ->subject('Verify Email Address')
- ->line('Click the button below to verify your email address.')
- ->action('Verify Email Address', $url);
- });
- }
-
-> [!NOTE]
+```php
+use Illuminate\Auth\Notifications\VerifyEmail;
+use Illuminate\Notifications\Messages\MailMessage;
+
+/**
+ * Bootstrap any application services.
+ */
+public function boot(): void
+{
+ // ...
+
+ VerifyEmail::toMailUsing(function (object $notifiable, string $url) {
+ return (new MailMessage)
+ ->subject('Verify Email Address')
+ ->line('Click the button below to verify your email address.')
+ ->action('Verify Email Address', $url);
+ });
+}
+```
+
+> [!NOTE]
> To learn more about mail notifications, please consult the [mail notification documentation](/docs/{{version}}/notifications#mail-notifications).
diff --git a/views.md b/views.md
index d57a46f1cc..f162919bf8 100644
--- a/views.md
+++ b/views.md
@@ -31,11 +31,13 @@ Views separate your controller / application logic from your presentation logic
Since this view is stored at `resources/views/greeting.blade.php`, we may return it using the global `view` helper like so:
- Route::get('/', function () {
- return view('greeting', ['name' => 'James']);
- });
+```php
+Route::get('/', function () {
+ return view('greeting', ['name' => 'James']);
+});
+```
-> [!NOTE]
+> [!NOTE]
> Looking for more information on how to write Blade templates? Check out the full [Blade documentation](/docs/{{version}}/blade) to get started.
@@ -43,7 +45,7 @@ Since this view is stored at `resources/views/greeting.blade.php`, we may return
Instead of writing their frontend templates in PHP via Blade, many developers have begun to prefer to write their templates using React or Vue. Laravel makes this painless thanks to [Inertia](https://inertiajs.com/), a library that makes it a cinch to tie your React / Vue frontend to your Laravel backend without the typical complexities of building an SPA.
-Our Breeze and Jetstream [starter kits](/docs/{{version}}/starter-kits) give you a great starting point for your next Laravel application powered by Inertia. In addition, the [Laravel Bootcamp](https://bootcamp.laravel.com) provides a full demonstration of building a Laravel application powered by Inertia, including examples in Vue and React.
+Our [React and Vue application starter kits](/docs/{{version}}/starter-kits) give you a great starting point for your next Laravel application powered by Inertia.
## Creating and Rendering Views
@@ -58,15 +60,19 @@ The `.blade.php` extension informs the framework that the file contains a [Blade
Once you have created a view, you may return it from one of your application's routes or controllers using the global `view` helper:
- Route::get('/', function () {
- return view('greeting', ['name' => 'James']);
- });
+```php
+Route::get('/', function () {
+ return view('greeting', ['name' => 'James']);
+});
+```
Views may also be returned using the `View` facade:
- use Illuminate\Support\Facades\View;
+```php
+use Illuminate\Support\Facades\View;
- return View::make('greeting', ['name' => 'James']);
+return View::make('greeting', ['name' => 'James']);
+```
As you can see, the first argument passed to the `view` helper corresponds to the name of the view file in the `resources/views` directory. The second argument is an array of data that should be made available to the view. In this case, we are passing the `name` variable, which is displayed in the view using [Blade syntax](/docs/{{version}}/blade).
@@ -75,9 +81,11 @@ As you can see, the first argument passed to the `view` helper corresponds to th
Views may also be nested within subdirectories of the `resources/views` directory. "Dot" notation may be used to reference nested views. For example, if your view is stored at `resources/views/admin/profile.blade.php`, you may return it from one of your application's routes / controllers like so:
- return view('admin.profile', $data);
+```php
+return view('admin.profile', $data);
+```
-> [!WARNING]
+> [!WARNING]
> View directory names should not contain the `.` character.
@@ -85,65 +93,75 @@ Views may also be nested within subdirectories of the `resources/views` director
Using the `View` facade's `first` method, you may create the first view that exists in a given array of views. This may be useful if your application or package allows views to be customized or overwritten:
- use Illuminate\Support\Facades\View;
+```php
+use Illuminate\Support\Facades\View;
- return View::first(['custom.admin', 'admin'], $data);
+return View::first(['custom.admin', 'admin'], $data);
+```
### Determining if a View Exists
If you need to determine if a view exists, you may use the `View` facade. The `exists` method will return `true` if the view exists:
- use Illuminate\Support\Facades\View;
+```php
+use Illuminate\Support\Facades\View;
- if (View::exists('admin.profile')) {
- // ...
- }
+if (View::exists('admin.profile')) {
+ // ...
+}
+```
## Passing Data to Views
As you saw in the previous examples, you may pass an array of data to views to make that data available to the view:
- return view('greetings', ['name' => 'Victoria']);
+```php
+return view('greetings', ['name' => 'Victoria']);
+```
When passing information in this manner, the data should be an array with key / value pairs. After providing data to a view, you can then access each value within your view using the data's keys, such as ``.
As an alternative to passing a complete array of data to the `view` helper function, you may use the `with` method to add individual pieces of data to the view. The `with` method returns an instance of the view object so that you can continue chaining methods before returning the view:
- return view('greeting')
- ->with('name', 'Victoria')
- ->with('occupation', 'Astronaut');
+```php
+return view('greeting')
+ ->with('name', 'Victoria')
+ ->with('occupation', 'Astronaut');
+```
### Sharing Data With All Views
Occasionally, you may need to share data with all views that are rendered by your application. You may do so using the `View` facade's `share` method. Typically, you should place calls to the `share` method within a service provider's `boot` method. You are free to add them to the `App\Providers\AppServiceProvider` class or generate a separate service provider to house them:
-
## View Composers
@@ -154,70 +172,74 @@ Typically, view composers will be registered within one of your application's [s
We'll use the `View` facade's `composer` method to register the view composer. Laravel does not include a default directory for class based view composers, so you are free to organize them however you wish. For example, you could create an `app/View/Composers` directory to house all of your application's view composers:
- with('count', $this->users->count());
- }
+ $view->with('count', $this->users->count());
}
+}
+```
As you can see, all view composers are resolved via the [service container](/docs/{{version}}/container), so you may type-hint any dependencies you need within a composer's constructor.
@@ -226,32 +248,38 @@ As you can see, all view composers are resolved via the [service container](/doc
You may attach a view composer to multiple views at once by passing an array of views as the first argument to the `composer` method:
- use App\Views\Composers\MultiComposer;
- use Illuminate\Support\Facades\View;
+```php
+use App\Views\Composers\MultiComposer;
+use Illuminate\Support\Facades\View;
- View::composer(
- ['profile', 'dashboard'],
- MultiComposer::class
- );
+View::composer(
+ ['profile', 'dashboard'],
+ MultiComposer::class
+);
+```
The `composer` method also accepts the `*` character as a wildcard, allowing you to attach a composer to all views:
- use Illuminate\Support\Facades;
- use Illuminate\View\View;
+```php
+use Illuminate\Support\Facades;
+use Illuminate\View\View;
- Facades\View::composer('*', function (View $view) {
- // ...
- });
+Facades\View::composer('*', function (View $view) {
+ // ...
+});
+```
### View Creators
View "creators" are very similar to view composers; however, they are executed immediately after the view is instantiated instead of waiting until the view is about to render. To register a view creator, use the `creator` method:
- use App\View\Creators\ProfileCreator;
- use Illuminate\Support\Facades\View;
+```php
+use App\View\Creators\ProfileCreator;
+use Illuminate\Support\Facades\View;
- View::creator('profile', ProfileCreator::class);
+View::creator('profile', ProfileCreator::class);
+```
## Optimizing Views
diff --git a/vite.md b/vite.md
index f002e40426..2611b84763 100644
--- a/vite.md
+++ b/vite.md
@@ -38,7 +38,7 @@
Laravel integrates seamlessly with Vite by providing an official plugin and Blade directive to load your assets for development and production.
-> [!NOTE]
+> [!NOTE]
> Are you running Laravel Mix? Vite has replaced Laravel Mix in new Laravel installations. For Mix documentation, please visit the [Laravel Mix](https://laravel-mix.com/) website. If you would like to switch to Vite, please see our [migration guide](https://github.com/laravel/vite-plugin/blob/main/UPGRADE.md#migrating-from-laravel-mix-to-vite).
@@ -56,7 +56,7 @@ Have you started a new Laravel application using our Vite scaffolding but need t
## Installation & Setup
-> [!NOTE]
+> [!NOTE]
> The following documentation discusses how to manually install and configure the Laravel Vite plugin. However, Laravel's [starter kits](/docs/{{version}}/starter-kits) already include all of this scaffolding and are the fastest way to get started with Laravel and Vite.
@@ -64,14 +64,14 @@ Have you started a new Laravel application using our Vite scaffolding but need t
You must ensure that Node.js (16+) and NPM are installed before running Vite and the Laravel plugin:
-```sh
+```shell
node -v
npm -v
```
You can easily install the latest version of Node and NPM using simple graphical installers from [the official Node website](https://nodejs.org/en/download/). Or, if you are using [Laravel Sail](https://laravel.com/docs/{{version}}/sail), you may invoke Node and NPM through Sail:
-```sh
+```shell
./vendor/bin/sail node -v
./vendor/bin/sail npm -v
```
@@ -81,7 +81,7 @@ You can easily install the latest version of Node and NPM using simple graphical
Within a fresh installation of Laravel, you will find a `package.json` file in the root of your application's directory structure. The default `package.json` file already includes everything you need to get started using Vite and the Laravel plugin. You may install your application's frontend dependencies via NPM:
-```sh
+```shell
npm install
```
@@ -175,7 +175,7 @@ export default defineConfig({
});
```
-If you are unable to generate a trusted certificate for your system, you may install and configure the [`@vitejs/plugin-basic-ssl` plugin](https://github.com/vitejs/vite-plugin-basic-ssl). When using untrusted certificates, you will need to accept the certificate warning for Vite's development server in your browser by following the "Local" link in your console when running the `npm run dev` command.
+If you are unable to generate a trusted certificate for your system, you may install and configure the [@vitejs/plugin-basic-ssl plugin](https://github.com/vitejs/vite-plugin-basic-ssl). When using untrusted certificates, you will need to accept the certificate warning for Vite's development server in your browser by following the "Local" link in your console when running the `npm run dev` command.
#### Running the Development Server in Sail on WSL2
@@ -195,7 +195,7 @@ export default defineConfig({
});
```
-If your file changes are not being reflected in the browser while the development server is running, you may also need to configure Vite's [`server.watch.usePolling` option](https://vitejs.dev/config/server-options.html#server-watch).
+If your file changes are not being reflected in the browser while the development server is running, you may also need to configure Vite's [server.watch.usePolling option](https://vitejs.dev/config/server-options.html#server-watch).
### Loading Your Scripts and Styles
@@ -310,7 +310,7 @@ export default defineConfig({
If you would like to build your frontend using the [Vue](https://vuejs.org/) framework, then you will also need to install the `@vitejs/plugin-vue` plugin:
-```sh
+```shell
npm install --save-dev @vitejs/plugin-vue
```
@@ -346,15 +346,15 @@ export default defineConfig({
});
```
-> [!NOTE]
-> Laravel's [starter kits](/docs/{{version}}/starter-kits) already include the proper Laravel, Vue, and Vite configuration. Check out [Laravel Breeze](/docs/{{version}}/starter-kits#breeze-and-inertia) for the fastest way to get started with Laravel, Vue, and Vite.
+> [!NOTE]
+> Laravel's [starter kits](/docs/{{version}}/starter-kits) already include the proper Laravel, Vue, and Vite configuration.These starter kits offer the fastest way to get started with Laravel, Vue, and Vite.
### React
If you would like to build your frontend using the [React](https://reactjs.org/) framework, then you will also need to install the `@vitejs/plugin-react` plugin:
-```sh
+```shell
npm install --save-dev @vitejs/plugin-react
```
@@ -384,8 +384,8 @@ You will also need to include the additional `@viteReactRefresh` Blade directive
The `@viteReactRefresh` directive must be called before the `@vite` directive.
-> [!NOTE]
-> Laravel's [starter kits](/docs/{{version}}/starter-kits) already include the proper Laravel, React, and Vite configuration. Check out [Laravel Breeze](/docs/{{version}}/starter-kits#breeze-and-inertia) for the fastest way to get started with Laravel, React, and Vite.
+> [!NOTE]
+> Laravel's [starter kits](/docs/{{version}}/starter-kits) already include the proper Laravel, React, and Vite configuration.These starter kits offer the fastest way to get started with Laravel, React, and Vite.
### Inertia
@@ -409,8 +409,8 @@ createInertiaApp({
If you are using Vite's code splitting feature with Inertia, we recommend configuring [asset prefetching](#asset-prefetching).
-> [!NOTE]
-> Laravel's [starter kits](/docs/{{version}}/starter-kits) already include the proper Laravel, Inertia, and Vite configuration. Check out [Laravel Breeze](/docs/{{version}}/starter-kits#breeze-and-inertia) for the fastest way to get started with Laravel, Inertia, and Vite.
+> [!NOTE]
+> Laravel's [starter kits](/docs/{{version}}/starter-kits) already include the proper Laravel, Inertia, and Vite configuration.These starter kits offer the fastest way to get started with Laravel, Inertia, and Vite.
### URL Processing
@@ -421,7 +421,7 @@ When referencing relative asset paths, you should remember that the paths are re
Consider the following project structure:
-```nothing
+```text
public/
taylor.png
resources/
@@ -445,19 +445,16 @@ The following example demonstrates how Vite will treat relative and absolute URL
## Working With Stylesheets
-You can learn more about Vite's CSS support within the [Vite documentation](https://vitejs.dev/guide/features.html#css). If you are using PostCSS plugins such as [Tailwind](https://tailwindcss.com), you may create a `postcss.config.js` file in the root of your project and Vite will automatically apply it:
+> [!NOTE]
+> Laravel's [starter kits](/docs/{{version}}/starter-kits) already include the proper Tailwind and Vite configuration. Or, if you would like to use Tailwind and Laravel without using one of our starter kits, check out [Tailwind's installation guide for Laravel](https://tailwindcss.com/docs/guides/laravel).
-```js
-export default {
- plugins: {
- tailwindcss: {},
- autoprefixer: {},
- },
-};
+All Laravel applications already include Tailwind and a properly configured `vite.config.js` file. So, you only need to start the Vite development server or run the `dev` Composer command, which will start both the Laravel and Vite development servers:
+
+```shell
+composer run dev
```
-> [!NOTE]
-> Laravel's [starter kits](/docs/{{version}}/starter-kits) already include the proper Tailwind, PostCSS, and Vite configuration. Or, if you would like to use Tailwind and Laravel without using one of our starter kits, check out [Tailwind's installation guide for Laravel](https://tailwindcss.com/docs/guides/laravel).
+Your application's CSS may be placed within the `resources/css/app.css` file.
## Working With Blade and Routes
@@ -528,7 +525,7 @@ export default defineConfig({
});
```
-Under the hood, the Laravel Vite plugin uses the [`vite-plugin-full-reload`](https://github.com/ElMassimo/vite-plugin-full-reload) package, which offers some advanced configuration options to fine-tune this feature's behavior. If you need this level of customization, you may provide a `config` definition:
+Under the hood, the Laravel Vite plugin uses the [vite-plugin-full-reload](https://github.com/ElMassimo/vite-plugin-full-reload) package, which offers some advanced configuration options to fine-tune this feature's behavior. If you need this level of customization, you may provide a `config` definition:
```js
import { defineConfig } from 'vite';
@@ -552,13 +549,15 @@ export default defineConfig({
It is common in JavaScript applications to [create aliases](#aliases) to regularly referenced directories. But, you may also create aliases to use in Blade by using the `macro` method on the `Illuminate\Support\Facades\Vite` class. Typically, "macros" should be defined within the `boot` method of a [service provider](/docs/{{version}}/providers):
- /**
- * Bootstrap any application services.
- */
- public function boot(): void
- {
- Vite::macro('image', fn (string $asset) => $this->asset("resources/images/{$asset}"));
- }
+```php
+/**
+ * Bootstrap any application services.
+ */
+public function boot(): void
+{
+ Vite::macro('image', fn (string $asset) => $this->asset("resources/images/{$asset}"));
+}
+```
Once a macro has been defined, it can be invoked within your templates. For example, we can use the `image` macro defined above to reference an asset located at `resources/images/logo.png`:
@@ -646,7 +645,7 @@ ASSET_URL=https://cdn.example.com
After configuring the asset URL, all re-written URLs to your assets will be prefixed with the configured value:
-```nothing
+```text
https://cdn.example.com/build/assets/app.9dce8d17.js
```
@@ -747,19 +746,19 @@ To ensure you don't forget to rebuild the SSR entry point, we recommend augmenti
Then, to build and start the SSR server, you may run the following commands:
-```sh
+```shell
npm run build
node bootstrap/ssr/ssr.js
```
If you are using [SSR with Inertia](https://inertiajs.com/server-side-rendering), you may instead use the `inertia:start-ssr` Artisan command to start the SSR server:
-```sh
+```shell
php artisan inertia:start-ssr
```
-> [!NOTE]
-> Laravel's [starter kits](/docs/{{version}}/starter-kits) already include the proper Laravel, Inertia SSR, and Vite configuration. Check out [Laravel Breeze](/docs/{{version}}/starter-kits#breeze-and-inertia) for the fastest way to get started with Laravel, Inertia SSR, and Vite.
+> [!NOTE]
+> Laravel's [starter kits](/docs/{{version}}/starter-kits) already include the proper Laravel, Inertia SSR, and Vite configuration.These starter kits offer the fastest way to get started with Laravel, Inertia SSR, and Vite.
## Script and Style Tag Attributes
@@ -767,7 +766,7 @@ php artisan inertia:start-ssr
### Content Security Policy (CSP) Nonce
-If you wish to include a [`nonce` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) on your script and style tags as part of your [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP), you may generate or specify a nonce using the `useCspNonce` method within a custom [middleware](/docs/{{version}}/middleware):
+If you wish to include a [nonce attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) on your script and style tags as part of your [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP), you may generate or specify a nonce using the `useCspNonce` method within a custom [middleware](/docs/{{version}}/middleware):
```php
### Subresource Integrity (SRI)
-If your Vite manifest includes `integrity` hashes for your assets, Laravel will automatically add the `integrity` attribute on any script and style tags it generates in order to enforce [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity). By default, Vite does not include the `integrity` hash in its manifest, but you may enable it by installing the [`vite-plugin-manifest-sri`](https://www.npmjs.com/package/vite-plugin-manifest-sri) NPM plugin:
+If your Vite manifest includes `integrity` hashes for your assets, Laravel will automatically add the `integrity` attribute on any script and style tags it generates in order to enforce [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity). By default, Vite does not include the `integrity` hash in its manifest, but you may enable it by installing the [vite-plugin-manifest-sri](https://www.npmjs.com/package/vite-plugin-manifest-sri) NPM plugin:
```shell
npm install --save-dev vite-plugin-manifest-sri
@@ -854,7 +853,7 @@ Vite::useIntegrityKey(false);
### Arbitrary Attributes
-If you need to include additional attributes on your script and style tags, such as the [`data-turbo-track`](https://turbo.hotwired.dev/handbook/drive#reloading-when-assets-change) attribute, you may specify them via the `useScriptTagAttributes` and `useStyleTagAttributes` methods. Typically, this methods should be invoked from a [service provider](/docs/{{version}}/providers):
+If you need to include additional attributes on your script and style tags, such as the [data-turbo-track](https://turbo.hotwired.dev/handbook/drive#reloading-when-assets-change) attribute, you may specify them via the `useScriptTagAttributes` and `useStyleTagAttributes` methods. Typically, this methods should be invoked from a [service provider](/docs/{{version}}/providers):
```php
use Illuminate\Support\Facades\Vite;
@@ -884,7 +883,7 @@ Vite::useStyleTagAttributes(fn (string $src, string $url, array|null $chunk, arr
]);
```
-> [!WARNING]
+> [!WARNING]
> The `$chunk` and `$manifest` arguments will be `null` while the Vite development server is running.