翻译进度
54
分块数量
1
参与人数

表单验证

这是一篇协同翻译的文章,你可以点击『我来翻译』按钮来参与翻译。


验证

简介

Laravel 提供了多种不同的方式来验证应用程序接收到的数据。最常见的方式是使用所有传入 HTTP 请求都可以使用的 validate 方法。不过,我们也会讨论其他验证方式。

Laravel 包含了各种方便的验证规则,你可以将这些规则应用于数据,甚至可以验证某个值在指定数据库表中是否唯一。我们将详细介绍这些验证规则中的每一项,以便你熟悉 Laravel 的所有验证功能。

无与伦比 翻译于 5天前

验证快速入门

为了了解 Laravel 强大的验证功能,让我们来看一个完整的示例,其中包括验证表单以及向用户显示错误消息。通过阅读这个高层次的概述,你将能够对如何使用 Laravel 验证传入的请求数据有一个良好的总体理解:

定义路由

首先,假设我们在 routes/web.php 文件中定义了以下路由:

use App\Http\Controllers\PostController;

Route::get('/post/create', [PostController::class, 'create']);
Route::post('/post', [PostController::class, 'store']);

GET 路由将显示一个供用户创建新博客文章的表单,而 POST 路由会将新的博客文章存储到数据库中。

创建控制器

接下来,让我们看一个用于处理这些路由传入请求的简单控制器。我们暂时将 store 方法留空:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class PostController extends Controller
{
    /**
     * 显示用于创建新博客文章的表单。
     */
    public function create(): View
    {
        return view('post.create');
    }

    /**
     * 存储新的博客文章。
     */
    public function store(Request $request): RedirectResponse
    {
        // 验证并存储博客文章...

        $post = /** ... */

        return to_route('post.show', ['post' => $post->id]);
    }
}

编写验证逻辑

现在,我们可以在 store 方法中填入用于验证新博客文章的逻辑。为此,我们将使用 Illuminate\Http\Request 对象提供的 validate 方法。如果验证规则通过,你的代码将继续正常执行;但是,如果验证失败,将抛出一个 Illuminate\Validation\ValidationException 异常,并且会自动向用户返回适当的错误响应。

无与伦比 翻译于 5天前

如果在传统 HTTP 请求期间验证失败,将会生成一个重定向到上一个 URL 的响应。如果传入请求是 XHR 请求,则会返回一个包含验证错误消息的 JSON 响应

为了更好地理解 validate 方法,让我们回到 store 方法:

/**
 * 存储新的博客文章。
 */
public function store(Request $request): RedirectResponse
{
    $validated = $request->validate([
        'title' => ['required', 'unique:posts', 'max:255'],
        'body' => ['required'],
    ]);

    // 博客文章有效...

    return redirect('/posts');
}

如你所见,验证规则被传递给 validate 方法。不用担心——所有可用的验证规则都有文档说明。再次说明,如果验证失败,会自动生成适当的响应。如果验证通过,我们的控制器将继续正常执行。

此外,你还可以使用 validateWithBag 方法验证请求,并将所有错误消息存储在一个命名错误包中:

$validated = $request->validateWithBag('post', [
    'title' => ['required', 'unique:posts', 'max:255'],
    'body' => ['required'],
]);

在第一次验证失败时停止

有时,你可能希望某个属性在第一次验证失败后就停止继续执行验证规则。为此,可以为该属性指定 bail 规则:

$request->validate([
    'title' => ['bail', 'required', 'unique:posts', 'max:255'],
    'body' => ['required'],
]);

在这个示例中,如果 title 属性上的 unique 规则验证失败,则不会再检查 max 规则。规则将按照它们被指定的顺序进行验证。

关于嵌套属性的说明

无与伦比 翻译于 5天前

如果传入的 HTTP 请求包含“嵌套”字段数据,你可以在验证规则中使用“点”语法来指定这些字段:

$request->validate([
    'title' => ['required', 'unique:posts', 'max:255'],
    'author.name' => ['required'],
    'author.description' => ['required'],
]);

另一方面,如果你的字段名称中包含一个字面意义上的句点,你可以通过使用反斜杠转义该句点,明确防止它被解释为“点”语法:

$request->validate([
    'title' => ['required', 'unique:posts', 'max:255'],
    'v1\.0' => ['required'],
]);

显示验证错误

那么,如果传入请求中的字段没有通过给定的验证规则会怎样?如前所述,Laravel 会自动将用户重定向回他们之前的位置。此外,所有验证错误和请求输入都会自动被闪存到 session 中

Illuminate\View\Middleware\ShareErrorsFromSession 中间件会将一个 $errors 变量共享给应用程序的所有视图,该中间件由 web 中间件组提供。当应用了该中间件后,视图中将始终可以使用 $errors 变量,因此你可以方便地假定 $errors 变量始终已定义,并且可以安全使用。$errors 变量将是一个 Illuminate\Support\MessageBag 实例。有关如何使用此对象的更多信息,请查看其文档

因此,在我们的示例中,当验证失败时,用户将被重定向到控制器的 create 方法,从而允许我们在视图中显示错误消息:

<!-- /resources/views/post/create.blade.php -->

<h1>创建文章</h1>

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<!-- 创建文章表单 -->
无与伦比 翻译于 5天前

自定义错误消息

Laravel 的每个内置验证规则都有一条错误消息,这些消息位于应用程序的 lang/en/validation.php 文件中。如果你的应用程序没有 lang 目录,可以使用 lang:publish Artisan 命令让 Laravel 创建它。

lang/en/validation.php 文件中,你会找到每条验证规则对应的翻译条目。你可以根据应用程序的需要自由更改或修改这些消息。

此外,你还可以将此文件复制到其他语言目录中,以便将这些消息翻译成应用程序所使用的语言。要了解更多关于 Laravel 本地化的信息,请查看完整的本地化文档

[!警告]
默认情况下,Laravel 应用程序骨架不包含 lang 目录。如果你想自定义 Laravel 的语言文件,可以通过 lang:publish Artisan 命令发布它们。

XHR 请求和验证

在这个示例中,我们使用传统表单向应用程序发送数据。然而,许多应用程序会从由 JavaScript 驱动的前端接收 XHR 请求。在 XHR 请求期间使用 validate 方法时,Laravel 不会生成重定向响应。相反,Laravel 会生成一个包含所有验证错误的 JSON 响应。这个 JSON 响应会以 422 HTTP 状态码发送。

@error 指令

你可以使用 @error Blade 指令快速判断某个给定属性是否存在验证错误消息。在 @error 指令中,你可以输出 $message 变量来显示错误消息:

<!-- /resources/views/post/create.blade.php -->

<label for="title">文章标题</label>

<input
    id="title"
    type="text"
    name="title"
    class="@error('title') is-invalid @enderror"
/>

@error('title')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror
无与伦比 翻译于 5天前

如果你正在使用命名错误包,可以将错误包的名称作为第二个参数传递给 @error 指令:

<input ... class="@error('title', 'post') is-invalid @enderror">

重新填充表单

当 Laravel 因验证错误生成重定向响应时,框架会自动将请求中的所有输入闪存到 session 中。这样做是为了让你能够在下一次请求期间方便地访问这些输入,并重新填充用户之前尝试提交的表单。

要获取上一次请求中闪存的输入,可以在 Illuminate\Http\Request 实例上调用 old 方法。old 方法会从 session 中取出之前闪存的输入数据:

$title = $request->old('title');

Laravel 还提供了一个全局的 old 辅助函数。如果你在 Blade 模板 中显示旧输入,使用 old 辅助函数来重新填充表单会更加方便。如果给定字段不存在旧输入,则会返回 null

<input type="text" name="title" value="{{ old('title') }}">

关于可选字段的说明

默认情况下,Laravel 会在应用程序的全局中间件栈中包含 TrimStringsConvertEmptyStringsToNull 中间件。因此,如果你不希望验证器将 null 值视为无效,通常需要将“可选”请求字段标记为 nullable。例如:

$request->validate([
    'title' => ['required', 'unique:posts', 'max:255'],
    'body' => ['required'],
    'publish_at' => ['nullable', 'date'],
]);
无与伦比 翻译于 4天前

在这个示例中,我们指定 publish_at 字段可以是 null,也可以是一个有效的日期表示。如果没有在规则定义中添加 nullable 修饰符,验证器会将 null 视为无效日期。

验证错误响应格式

当你的应用程序抛出 Illuminate\Validation\ValidationException 异常,并且传入的 HTTP 请求期望接收 JSON 响应时,Laravel 会自动为你格式化错误消息,并返回一个 422 Unprocessable Entity HTTP 响应。

下面,你可以查看一个验证错误的 JSON 响应格式示例。请注意,嵌套的错误键会被扁平化为“点”表示法格式:

{
    "message": "The team name must be a string. (and 4 more errors)",
    "errors": {
        "team_name": [
            "The team name must be a string.",
            "The team name must be at least 1 characters."
        ],
        "authorization.role": [
            "The selected authorization.role is invalid."
        ],
        "users.0.email": [
            "The users.0.email field is required."
        ],
        "users.2.email": [
            "The users.2.email must be a valid email address."
        ]
    }
}

表单请求验证

创建表单请求

对于更复杂的验证场景,你可能希望创建一个“表单请求”。表单请求是自定义的请求类,它们封装了自身的验证和授权逻辑。要创建一个表单请求类,你可以使用 make:request Artisan CLI 命令:

php artisan make:request StorePostRequest

生成的表单请求类将放置在 app/Http/Requests 目录中。如果该目录不存在,当你运行 make:request 命令时会自动创建。Laravel 生成的每个表单请求都有两个方法:authorizerules

无与伦比 翻译于 4天前

正如你可能已经猜到的,authorize 方法负责确定当前已通过身份验证的用户是否可以执行该请求所代表的操作,而 rules 方法则返回应该应用于请求数据的验证规则:

/**
 * 获取应用于该请求的验证规则。
 *
 * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
 */
public function rules(): array
{
    return [
        'title' => ['required', 'unique:posts', 'max:255'],
        'body' => ['required'],
    ];
}

[!注意]
你可以在 rules 方法的签名中对所需的任何依赖项进行类型提示。它们会通过 Laravel 服务容器自动解析。

那么,验证规则是如何被执行的呢?你只需要在控制器方法中对该请求进行类型提示即可。传入的表单请求会在控制器方法被调用之前进行验证,这意味着你不需要在控制器中加入任何验证逻辑:

/**
 * 存储新的博客文章。
 */
public function store(StorePostRequest $request): RedirectResponse
{
    // 传入的请求有效...

    // 获取已验证的输入数据...
    $validated = $request->validated();

    // 获取已验证输入数据的一部分...
    $validated = $request->safe()->only(['name', 'email']);
    $validated = $request->safe()->except(['name', 'email']);

    // 存储博客文章...

    return redirect('/posts');
}

如果验证失败,将生成一个重定向响应,把用户发送回之前的位置。错误信息也会被闪存到 session 中,以便进行显示。如果该请求是 XHR 请求,则会向用户返回一个状态码为 422 的 HTTP 响应,其中包含验证错误的 JSON 表示

[!注意]
需要为由 Inertia 驱动的 Laravel 前端添加实时表单请求验证吗?请查看 Laravel Precognition

无与伦比 翻译于 4天前

执行额外验证

有时,你需要在初始验证完成后执行额外的验证。你可以使用表单请求的 after 方法来实现这一点。

after 方法应返回一个可调用对象或闭包组成的数组,这些内容会在验证完成后被调用。给定的可调用对象会接收一个 Illuminate\Validation\Validator 实例,使你可以在必要时添加额外的错误消息:

use Illuminate\Validation\Validator;

/**
 * 获取请求的“after”验证可调用对象。
 */
public function after(): array
{
    return [
        function (Validator $validator) {
            if ($this->somethingElseIsInvalid()) {
                $validator->errors()->add(
                    'field',
                    'Something is wrong with this field!'
                );
            }
        }
    ];
}

如前所述,after 方法返回的数组也可以包含可调用类。这些类的 __invoke 方法将接收一个 Illuminate\Validation\Validator 实例:

use App\Validation\ValidateShippingTime;
use App\Validation\ValidateUserStatus;
use Illuminate\Validation\Validator;

/**
 * 获取请求的“after”验证可调用对象。
 */
public function after(): array
{
    return [
        new ValidateUserStatus,
        new ValidateShippingTime,
        function (Validator $validator) {
            //
        }
    ];
}

在第一次验证失败时停止

通过向你的请求类添加 StopOnFirstFailure 属性,你可以通知验证器,一旦发生一次验证失败,就应该停止验证所有属性:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\Attributes\StopOnFirstFailure;
use Illuminate\Foundation\Http\FormRequest;

#[StopOnFirstFailure]
class StorePostRequest extends FormRequest
{
    // ...
}

遇到未知字段时失败

通过向你的请求类添加 FailOnUnknownFields 属性,你可以指示 Laravel 拒绝任何未在请求验证规则中定义的传入字段:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\Attributes\FailOnUnknownFields;
use Illuminate\Foundation\Http\FormRequest;

#[FailOnUnknownFields]
class StorePostRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'title' => ['required', 'string'],
            'body' => ['required', 'string'],
        ];
    }
}
无与伦比 翻译于 4天前

你也可以在 AppServiceProvider 中为所有表单请求全局启用此行为:

use Illuminate\Foundation\Http\FormRequest;

/**
 * 启动任何应用程序服务。
 */
public function boot(): void
{
    FormRequest::failOnUnknownFields();
}

如果需要,你可以通过向该属性传递 false,为特定请求禁用此行为:

#[FailOnUnknownFields(false)]
class PublicWebhookRequest extends FormRequest
{
    // ...
}

拒绝未知字段可以通过阻止意外的输入键进一步流入你的应用程序,为防止类似批量赋值的问题提供额外保护。不过,你仍然应该配置模型的 $fillable / $guarded 属性,并且只持久化可信的、经过验证的输入。

自定义重定向位置

当表单请求验证失败时,会生成一个重定向响应,将用户发送回之前的位置。不过,你可以自由自定义此行为。为此,你可以在表单请求上使用 RedirectTo 属性:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\Attributes\RedirectTo;
use Illuminate\Foundation\Http\FormRequest;

#[RedirectTo('/dashboard')]
class StorePostRequest extends FormRequest
{
    // ...
}

或者,如果你希望将用户重定向到一个命名路由,可以改用 RedirectToRoute 属性:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\Attributes\RedirectToRoute;
use Illuminate\Foundation\Http\FormRequest;

#[RedirectToRoute('dashboard')]
class StorePostRequest extends FormRequest
{
    // ...
}

自定义错误包

当表单请求验证失败时,错误会被闪存到 default 错误包中。如果你需要将错误存储到另一个命名错误包中,可以在表单请求上使用 ErrorBag 属性:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\Attributes\ErrorBag;
use Illuminate\Foundation\Http\FormRequest;

#[ErrorBag('login')]
class LoginRequest extends FormRequest
{
    // ...
}
无与伦比 翻译于 4天前

Authorizing Form Requests

The form request class also contains an authorize method. Within this method, you may determine if the authenticated user actually has the authority to update a given resource. For example, you may determine if a user actually owns a blog comment they are attempting to update. Most likely, you will interact with your authorization gates and policies within this method:

use App\Models\Comment;

/**
 * Determine if the user is authorized to make this request.
 */
public function authorize(): bool
{
    $comment = Comment::find($this->route('comment'));

    return $comment && $this->user()->can('update', $comment);
}

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

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

Therefore, if your application is taking advantage of route model binding, your code may be made even more succinct by accessing the resolved model as a property of the request:

return $this->user()->can('update', $this->comment);

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

If you plan to handle authorization logic for the request in another part of your application, you may remove the authorize method completely, or simply return true:

/**
 * Determine if the user is authorized to make this request.
 */
public function authorize(): bool
{
    return true;
}

[!NOTE]
You may type-hint any dependencies you need within the authorize method's signature. They will automatically be resolved via the Laravel service container.

Customizing the Error Messages

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

/**
 * Get the error messages for the defined validation rules.
 *
 * @return array<string, string>
 */
public function messages(): array
{
    return [
        'title.required' => 'A title is required',
        'body.required' => 'A message is required',
    ];
}

Customizing the Validation Attributes

Many of Laravel's built-in validation rule error messages contain an :attribute placeholder. If you would like the :attribute placeholder of your validation message to be replaced with a custom attribute name, you may specify the custom names by overriding the attributes method. This method should return an array of attribute / name pairs:

/**
 * Get custom attributes for validator errors.
 *
 * @return array<string, string>
 */
public function attributes(): array
{
    return [
        'email' => 'email address',
    ];
}

Preparing Input for Validation

If you need to prepare or sanitize any data from the request before you apply your validation rules, you may use the prepareForValidation method:

use Illuminate\Support\Str;

/**
 * Prepare the data for validation.
 */
protected function prepareForValidation(): void
{
    $this->merge([
        'slug' => Str::slug($this->slug),
    ]);
}

Likewise, if you need to normalize any request data after validation is complete, you may use the passedValidation method:

/**
 * Handle a passed validation attempt.
 */
protected function passedValidation(): void
{
    $this->replace(['name' => 'Taylor']);
}

Manually Creating Validators

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

<?php

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PostController extends Controller
{
    /**
     * Store a new blog post.
     */
    public function store(Request $request): RedirectResponse
    {
        $validator = Validator::make($request->all(), [
            'title' => ['required', 'unique:posts', 'max:255'],
            'body' => ['required'],
        ]);

        if ($validator->fails()) {
            return redirect('/post/create')
                ->withErrors($validator)
                ->withInput();
        }

        // Retrieve the validated input...
        $validated = $validator->validated();

        // Retrieve a portion of the validated input...
        $validated = $validator->safe()->only(['name', 'email']);
        $validated = $validator->safe()->except(['name', 'email']);

        // Store the blog post...

        return redirect('/posts');
    }
}

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.

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.

Stopping on First 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()) {
    // ...
}

Automatic Redirection

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:

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

You may use the validateWithBag method to store the error messages in a named error bag if validation fails:

Validator::make($request->all(), [
    'title' => ['required', 'unique:posts', 'max:255'],
    'body' => ['required'],
])->validateWithBag('post');

Named Error Bags

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:

return redirect('/register')->withErrors($validator, 'login');

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

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

Customizing the Error Messages

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:

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

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:

$messages = [
    'same' => 'The :attribute and :other must match.',
    'size' => 'The :attribute must be exactly :size.',
    'between' => 'The :attribute value :input is not between :min - :max.',
    'in' => 'The :attribute must be one of the following types: :values',
];

Specifying a Custom Message for a Given Attribute

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:

$messages = [
    'email.required' => 'We need to know your email address!',
];

Specifying Custom Attribute Values

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:

$validator = Validator::make($input, $rules, $messages, [
    'email' => 'email address',
]);

Performing Additional Validation

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:

use Illuminate\Support\Facades\Validator;

$validator = Validator::make(/* ... */);

$validator->after(function ($validator) {
    if ($this->somethingElseIsInvalid()) {
        $validator->errors()->add(
            'field', 'Something is wrong with this field!'
        );
    }
});

if ($validator->fails()) {
    // ...
}

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:

use App\Validation\ValidateShippingTime;
use App\Validation\ValidateUserStatus;

$validator->after([
    new ValidateUserStatus,
    new ValidateShippingTime,
    function ($validator) {
        // ...
    },
]);

Working With Validated Input

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:

$validated = $request->validated();

$validated = $validator->validated();

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:

$validated = $request->safe()->only(['name', 'email']);

$validated = $request->safe()->except(['name', 'email']);

$validated = $request->safe()->all();

In addition, the Illuminate\Support\ValidatedInput instance may be iterated over and accessed like an array:

// Validated data may be iterated...
foreach ($request->safe() as $key => $value) {
    // ...
}

// Validated data may be accessed as an array...
$validated = $request->safe();

$email = $validated['email'];

If you would like to add additional fields to the validated data, you may call the merge method:

$validated = $request->safe()->merge(['name' => 'Taylor Otwell']);

If you would like to retrieve the validated data as a collection instance, you may call the collect method:

$collection = $request->safe()->collect();

Working With Error Messages

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

Retrieving the First Error Message for a Field

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

$errors = $validator->errors();

echo $errors->first('email');

Retrieving All Error Messages for a Field

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

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

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

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

Retrieving All Error Messages for All Fields

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

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

Determining if Messages Exist for a Field

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

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

Specifying Custom Messages in Language Files

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.

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.

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.

[!WARNING]
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.

Custom Messages for Specific Attributes

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:

'custom' => [
    'email' => [
        'required' => 'We need to know your email address!',
        'max' => 'Your email address is too long!'
    ],
],

Specifying Attributes in Language Files

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:

'attributes' => [
    'email' => 'email address',
],

[!WARNING]
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.

Specifying Values in Language Files

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:

Validator::make($request->all(), [
    'credit_card_number' => ['required_if:payment_type,cc']
]);

If this validation rule fails, it will produce the following error message:

The credit card number field is required when payment type is cc.

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:

'values' => [
    'payment_type' => [
        'cc' => 'credit card'
    ],
],

[!WARNING]
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.

After defining this value, the validation rule will produce the following error message:

The credit card number field is required when payment type is credit card.

Available Validation Rules

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

Booleans

Strings

Numbers

Arrays

Dates

Files

Database

Utilities

accepted

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

accepted_if:anotherfield,value,...

The field under validation must be "yes", "on", 1, "1", true, 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.

active_url

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.

after:date

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']

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']

For convenience, date-based rules may be constructed using the fluent date rule builder:

use Illuminate\Validation\Rule;

'start_date' => [
    'required',
    Rule::date()->after(today()->addDays(7)),
],

The afterToday and todayOrAfter methods may be used to fluently express the date and must be after today, or today or after, respectively:

'start_date' => [
    'required',
    Rule::date()->afterToday(),
],

after_or_equal:date

The field under validation must be a value after or equal to the given date. For more information, see the after rule.

For convenience, date-based rules may be constructed using the fluent date rule builder:

use Illuminate\Validation\Rule;

'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:

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} and \p{M}.

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:

'username' => ['alpha:ascii'],

alpha_dash

The field under validation must be entirely Unicode alpha-numeric characters contained in \p{L}, \p{M}, \p{N}, as well as ASCII dashes (-) and ASCII underscores (_).

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:

'username' => ['alpha_dash:ascii'],

alpha_num

The field under validation must be entirely Unicode alpha-numeric characters contained in \p{L}, \p{M}, and \p{N}.

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:

'username' => ['alpha_num:ascii'],

array

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;

$input = [
    'user' => [
        'name' => 'Taylor Otwell',
        'username' => 'taylorotwell',
        'admin' => true,
    ],
];

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.

ascii

The field under validation must be entirely 7-bit ASCII characters.

bail

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()) {
    // ...
}

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, 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;

'start_date' => [
    'required',
    Rule::date()->before(today()->subDays(7)),
],

The beforeToday and todayOrBefore methods may be used to fluently express the date and must be before today, or today or before, respectively:

'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, 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;

'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.

boolean

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

You may use the strict parameter to only consider the field valid if its value is true or false:

'foo' => ['boolean:strict']

confirmed

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.

You may also pass a custom confirmation field name. For example, confirmed:repeat_username will expect the field repeat_username to match the field under validation.

contains:foo,bar,...

The field under validation must be an array that contains all of the given parameter values. Since this rule often requires you to implode an array, the Rule::contains method may be used to fluently construct the rule:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

Validator::make($data, [
    'roles' => [
        'required',
        'array',
        Rule::contains(['admin', 'editor']),
    ],
]);

doesnt_contain:foo,bar,...

The field under validation must be an array that does not contain any of the given parameter values. Since this rule often requires you to implode an array, the Rule::doesntContain method may be used to fluently construct the rule:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

Validator::make($data, [
    'roles' => [
        'required',
        'array',
        Rule::doesntContain(['admin', 'editor']),
    ],
]);

current_password

The field under validation must match the authenticated user's password. You may specify an authentication guard using the rule's first parameter:

'password' => ['current_password:api']

date

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

date_equals:date

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.

date_format:format,...

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 class.

For convenience, date-based rules may be constructed using the fluent date rule builder:

use Illuminate\Validation\Rule;

'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']

// Must have between 2 and 4 decimal places...
'price' => ['decimal:2,4']

declined

The field under validation must be "no", "off", 0, "0", false, or "false".

declined_if:anotherfield,value,...

The field under validation must be "no", "off", 0, "0", false, or "false" if another field under validation is equal to a specified value.

different:field

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

digits:value

The integer under validation must have an exact length of value.

digits_between:min,max

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

dimensions

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

'avatar' => ['dimensions:min_width=100,min_height=200']

Available constraints are: min_width, max_width, min_height, max_height, width, height, ratio, min_ratio, max_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']

The min_ratio and max_ratio constraints may be used to define a range of acceptable aspect ratios:

'avatar' => ['dimensions:min_ratio=1/2,max_ratio=3/2']

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;

Validator::make($data, [
    'avatar' => [
        'required',
        Rule::dimensions()
            ->maxWidth(1000)
            ->maxHeight(500)
            ->ratio(3 / 2),
    ],
]);

You may also use the minRatio, maxRatio, and ratioBetween methods to fluently define ratio constraints:

Rule::dimensions()->ratioBetween(min: 1 / 2, max: 3 / 2)

distinct

When validating arrays, the field under validation must not have any duplicate values:

'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']

You may add ignore_case to the validation rule's arguments to make the rule ignore capitalization differences:

'foo.*.id' => ['distinct:ignore_case']

doesnt_start_with:foo,bar,...

The field under validation must not start with one of the given values.

doesnt_end_with:foo,bar,...

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 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']

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 supported RFCs.
  • strict: NoRFCWarningsValidation - Validate the email according to 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.
  • filter_unicode: FilterEmailValidation::unicode() - Ensure the email address is valid according to PHP's filter_var function, allowing some Unicode characters.

For convenience, email validation rules may be built using the fluent rule builder:

use Illuminate\Validation\Rule;

$request->validate([
    'email' => [
        'required',
        Rule::email()
            ->rfcCompliant(strict: false)
            ->validateMxRecord()
            ->preventSpoofing()
    ],
]);

[!WARNING]
The dns and spoof validators require the PHP intl extension.

encoding:encoding_type

The field under validation must match the specified character encoding. This rule uses PHP's mb_check_encoding function to verify the encoding of the given file or string value. For convenience, the encoding rule may be constructed using Laravel's fluent file rule builder:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\File;

Validator::validate($input, [
    'attachment' => [
        'required',
        File::types(['csv'])
            ->encoding('utf-8'),
    ],
]);

ends_with:foo,bar,...

The field under validation must end with one of the given values.

enum

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;

$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]);

Rule::enum(ServerStatus::class)
    ->except([ServerStatus::Pending, ServerStatus::Active]);

The when method may be used to conditionally modify the Enum rule:

use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

Rule::enum(ServerStatus::class)
    ->when(
        Auth::user()->isAdmin(),
        fn ($rule) => $rule->only(...),
        fn ($rule) => $rule->only(...),
    );

exclude

The field under validation will be excluded from the request data returned by the validate and validated methods.

exclude_if:anotherfield,value

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.

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;

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)],
]);

exclude_unless:anotherfield,value

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.

If complex conditional exclusion logic is required, you may utilize the Rule::excludeUnless 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 not be excluded:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

Validator::make($request->all(), [
    'role_id' => [Rule::excludeUnless($request->user()->is_admin)],
]);

Validator::make($request->all(), [
    'role_id' => [Rule::excludeUnless(fn () => $request->user()->is_admin)],
]);

exclude_with:anotherfield

The field under validation will be excluded from the request data returned by the validate and validated methods if the anotherfield field is present.

exclude_without:anotherfield

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.

exists:table,column

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

Basic Usage of Exists Rule

'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.

Specifying a Custom Column Name

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']

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']

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']

If you would like to customize the query executed by the validation rule, you may use the Rule class to fluently define the rule.

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);
        }),
    ],
]);

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')],

Sometimes, you may wish to validate whether an array of values exists in the database. You can do so by adding both the exists and array rules to the field being validated:

'states' => ['array', Rule::exists('states', 'abbreviation')],

When both of these rules are assigned to a field, Laravel will automatically build a single query to determine if all of the given values exist in the specified table.

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'],

[!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 or mimetypes rules.

file

The field under validation must be a successfully uploaded file.

filled

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.

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.

hex_color

The field under validation must contain a valid color value in hexadecimal format.

image

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;

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;

$input = [
    'airports' => ['NYC', 'LAS'],
];

Validator::make($input, [
    'airports' => [
        'required',
        'array',
    ],
    'airports.*' => Rule::in(['NYC', 'LIT']),
]);

in_array:anotherfield.*

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

in_array_keys:value.*

The field under validation must be an array having at least one of the given values as a key within the array:

'config' => ['array', 'in_array_keys:timezone']

integer

The field under validation must be an integer.

You may use the strict parameter to only consider the field valid if its type is integer. Strings with integer values will be considered invalid:

'age' => ['integer:strict']

[!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.

ip

The field under validation must be an IP address.

ipv4

The field under validation must be an IPv4 address.

ipv6

The field under validation must be an IPv6 address.

json

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.

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.

lowercase

The field under validation must be lowercase.

list

The field under validation must be an array that is a list. An array is considered a list if its keys consist of consecutive numbers from 0 to count($array) - 1.

mac_address

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.

max_digits:value

The integer under validation must have a maximum length of value.

mimetypes:text/plain,...

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

'video' => ['mimetypes:video/avi,video/mpeg,video/quicktime'],

'media' => ['mimetypes:image/*,video/*'],

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.

mimes:foo,bar,...

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

'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:

svn.apache.org/repos/asf/httpd/htt...

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.

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.

min_digits:value

The integer under validation must have a minimum length of value.

multiple_of:value

The field under validation must be a multiple of value.

missing

The field under validation must not be present in the input data.

missing_if:anotherfield,value,...

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

missing_unless:anotherfield,value

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

missing_with:foo,bar,...

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

missing_with_all:foo,bar,...

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

not_in:foo,bar,...

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;

Validator::make($data, [
    'toppings' => [
        'required',
        Rule::notIn(['sprinkles', 'cherries']),
    ],
]);

not_regex:pattern

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'].

nullable

The field under validation may be null.

numeric

The field under validation must be numeric.

You may use the strict parameter to only consider the field valid if its value is an integer or float type. Numeric strings will be considered invalid:

'amount' => ['numeric:strict']

present

The field under validation must exist in the input data.

present_if:anotherfield,value,...

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

present_unless:anotherfield,value

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

present_with:foo,bar,...

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

present_with_all:foo,bar,...

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

prohibited

The field under validation must be missing or empty. A field is "empty" if it meets one of the following criteria:

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

prohibited_if:anotherfield,value,...

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:

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

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;

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)],
]);

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,...

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:

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

If complex conditional prohibition logic is required, you may utilize the Rule::prohibitedUnless 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 not be prohibited:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

Validator::make($request->all(), [
    'role_id' => [Rule::prohibitedUnless($request->user()->is_admin)],
]);

Validator::make($request->all(), [
    'role_id' => [Rule::prohibitedUnless(fn () => $request->user()->is_admin)],
]);

prohibits:anotherfield,...

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:

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

regex:pattern

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'].

required

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:

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

required_if:anotherfield,value,...

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

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;

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)],
]);

required_if_accepted:anotherfield,...

The field under validation must be present and not empty if the anotherfield field is equal to "yes", "on", 1, "1", true, or "true".

required_if_declined:anotherfield,...

The field under validation must be present and not empty if the anotherfield field is equal to "no", "off", 0, "0", false, or "false".

required_unless:anotherfield,value,...

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.

If you would like to construct a more complex condition for the required_unless rule, you may use the Rule::requiredUnless 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 not required:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

Validator::make($request->all(), [
    'role_id' => [Rule::requiredUnless($request->user()->is_admin)],
]);

Validator::make($request->all(), [
    'role_id' => [Rule::requiredUnless(fn () => $request->user()->is_admin)],
]);

required_with:foo,bar,...

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

required_with_all:foo,bar,...

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

required_without:foo,bar,...

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

required_without_all:foo,bar,...

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

required_array_keys:foo,bar,...

The field under validation must be an array and must contain at least the specified keys.

same:field

The given field must match the field under validation.

size:value

The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value (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'];

// 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 uploaded file is exactly 512 kilobytes...
'image' => ['file', 'size:512'];

starts_with:foo,bar,...

The field under validation must start with one of the given values.

string

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

For convenience, string validation rules may also be constructed using the fluent Rule::string() rule builder:

use Illuminate\Validation\Rule;

'title' => [
    'required',
    Rule::string()
        ->min(3)
        ->max(255)
        ->alphaDash(ascii: true),
],

The string rule builder provides methods for common string constraints, including alpha, alphaDash, alphaNumeric, ascii, between, doesntEndWith, doesntStartWith, endsWith, exactly, lowercase, max, min, startsWith, and uppercase. Since the rule builder is conditionable, you may also use the when and unless methods to conditionally apply constraints.

timezone

The field under validation must be a valid timezone identifier according to the DateTimeZone::listIdentifiers method.

The arguments accepted by the DateTimeZone::listIdentifiers method may also be provided to this validation rule:

'timezone' => ['required', 'timezone:all'];

'timezone' => ['required', 'timezone:Africa'];

'timezone' => ['required', 'timezone:per_country,US'];

unique:table,column

The field under validation must not exist within the given database table.

Specifying a Custom Table / Column Name:

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']

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']

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']

Forcing a Unique Rule to Ignore a Given ID:

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.

To instruct the validator to ignore the user's ID, we'll use the Rule class to fluently define the rule.

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users')->ignore($user->id),
    ],
]);

[!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)

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')

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)

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))

Ignoring Soft Deleted 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();

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');

uppercase

The field under validation must be uppercase.

url

The field under validation must be a valid URL.

If you would like to specify the URL protocols that should be considered valid, you may pass the protocols as validation rule parameters:

'url' => ['url:http,https'],

'game' => ['url:minecraft,steam'],

ulid

The field under validation must be a valid Universally Unique Lexicographically Sortable Identifier (ULID).

uuid

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:

'uuid' => ['uuid:4']

Conditionally Adding Rules

Skipping Validation When Fields Have Certain Values

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;

$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'],
]);

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'],
]);

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

[!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.

Complex Conditional Validation

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

use Illuminate\Support\Facades\Validator;

$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;

$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;
});

[!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.

Complex Conditional Array Validation

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',
        ],
    ],
];

$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';
});

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, 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;

$input = [
    'user' => [
        'name' => 'Taylor Otwell',
        'username' => 'taylorotwell',
        'admin' => true,
    ],
];

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.

Validating Nested Array Input

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;

$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(), [
    'users.*.email' => ['email', 'unique:users'],
    'users.*.first_name' => ['required_with:users.*.last_name'],
]);

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

'custom' => [
    'users.*.email' => [
        'unique' => 'Each user 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;

$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), :position (starts from 1), or :ordinal-position (starts from 1st) placeholders within your custom validation message:

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.',
]);

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.',

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;

Validator::validate($input, [
    'attachment' => [
        'required',
        File::types(['mp3', 'wav'])
            ->min(1024)
            ->max(12 * 1024),
    ],
]);

Validating File Types

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:

svn.apache.org/repos/asf/httpd/htt...

Validating File Sizes

For convenience, minimum and maximum file sizes may be specified as a string with a suffix indicating the file size units. The kb, mb, gb, and tb suffixes are supported:

File::types(['mp3', 'wav'])
    ->min('1kb')
    ->max('10mb');

Validating Image Files

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:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\File;

Validator::validate($input, [
    'photo' => [
        'required',
        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.

[!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

You may also validate the dimensions of an image. For example, to validate that an uploaded image is at least 1000 pixels wide and 500 pixels tall, you may use the dimensions rule:

use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\File;

File::image()->dimensions(
    Rule::dimensions()
        ->maxWidth(1000)
        ->maxHeight(500)
)

[!NOTE]
More information regarding validating image dimensions may be found in the dimension rule documentation.

Validating Passwords

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;

$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)

// 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 number...
Password::min(8)->numbers()

// 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()

Internally, the Password rule object uses the k-Anonymity model to determine if a password has been leaked via the 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);

Of course, you may chain all the methods in the examples above:

Password::min(8)
    ->letters()
    ->mixedCase()
    ->numbers()
    ->symbols()
    ->uncompromised()

You may convert a Password rule object to a string suitable for the HTML passwordrules attribute using the toPasswordRulesString method:

<input
    type="password"
    name="password"
    autocomplete="new-password"
    passwordrules="{{ Password::defaults()->toPasswordRulesString() }}"
/>

Defining Default Password Rules

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:

use Illuminate\Validation\Rules\Password;

/**
 * Bootstrap any application services.
 */
public function boot(): void
{
    Password::defaults(function () {
        $rule = Password::min(8);

        return $this->app->isProduction()
            ? $rule->mixedCase()->uncompromised()
            : $rule;
    });
}

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()],

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;

Password::defaults(function () {
    $rule = Password::min(8)->rules([new ZxcvbnRule]);

    // ...
});

Custom Validation Rules

Using Rule Objects

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:

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:

<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class Uppercase implements ValidationRule
{
    /**
     * Run the validation rule.
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (strtoupper($value) !== $value) {
            $fail('The :attribute must be uppercase.');
        }
    }
}

Once the rule has been defined, you may attach it to a validator by passing an instance of the rule object with your other validation rules:

use App\Rules\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 and instruct Laravel to translate the error message:

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');

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:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ValidationRule;

class Uppercase implements DataAwareRule, ValidationRule
{
    /**
     * All of the data under validation.
     *
     * @var array<string, mixed>
     */
    protected $data = [];

    // ...

    /**
     * Set the data under validation.
     *
     * @param  array<string, mixed>  $data
     */
    public function setData(array $data): static
    {
        $this->data = $data;

        return $this;
    }
}

Or, if your validation rule requires access to the validator instance performing the validation, you may implement the ValidatorAwareRule interface:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Contracts\Validation\ValidatorAwareRule;
use Illuminate\Validation\Validator;

class Uppercase implements ValidationRule, ValidatorAwareRule
{
    /**
     * The validator instance.
     *
     * @var \Illuminate\Validation\Validator
     */
    protected $validator;

    // ...

    /**
     * Set the current validator.
     */
    public function setValidator(Validator $validator): static
    {
        $this->validator = $validator;

        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.");
            }
        },
    ],
]);

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 will not be run against an empty string:

use Illuminate\Support\Facades\Validator;

$rules = ['name' => ['unique:users,name']];

$input = ['name' => ''];

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:

php artisan make:rule Uppercase --implicit

[!WARNING]
An "implicit" rule only implies that the attribute is required. Whether it actually invalidates a missing or empty attribute is up to you.

本文章首发在 LearnKu.com 网站上。

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
贡献者:1
讨论数量: 2
发起讨论 只看当前版本


xingxiaoli
自定义验证规则只能验证单个属性吗?
0 个点赞 | 7 个回复 | 问答 | 课程版本 5.8
sonw
嵌套验证 * 不起作用
0 个点赞 | 5 个回复 | 问答 | 课程版本 5.1