イントロダクションIntroduction
Laravelは、アプリケーションの受信データをバリデーションするために複数の異なるアプローチを提供します。すべての受信HTTPリクエストで使用可能なvalidate
メソッドを使用するのがもっとも一般的です。しかし、バリデーションに対する他のアプローチについても説明していきます。Laravel provides several
different approaches to validate your application's
incoming data. It is most common to use the
validate
method available on all
incoming HTTP requests. However, we will discuss
other approaches to validation as well.
Laravelは、データに適用する便利で数多くのバリデーションルールを持っており、特定のデータベーステーブルで値が一意であるかどうかをバリデーションする機能も提供しています。Laravelのすべてのバリデーション機能に精通できるよう、各バリデーションルールを詳しく説明します。Laravel includes a wide variety of convenient validation rules that you may apply to data, even providing the ability to validate if values are unique in a given database table. We'll cover each of these validation rules in detail so that you are familiar with all of Laravel's validation features.
クイックスタートValidation Quickstart
Laravelの強力なバリデーション機能について学ぶため、フォームをバリデーションし、エラーメッセージをユーザーに表示する完全な例を見てみましょう。この高レベルの概要を読むことで、Laravelを使用して受信リクエストデータをバリデーションする一般的な方法を理解できます。To learn about Laravel's powerful validation features, let's look at a complete example of validating a form and displaying the error messages back to the user. By reading this high-level overview, you'll be able to gain a good general understanding of how to validate incoming request data using Laravel:
ルート定義Defining the Routes
まず、routes/web.php
ファイルに以下のルートを定義してあるとしましょう。First, let's assume we have the
following routes defined in our
routes/web.php
file:
use App\Http\Controllers\PostController;
Route::get('/post/create', [PostController::class, 'create']);
Route::post('/post', [PostController::class, 'store']);
GET
のルートは新しいブログポストを作成するフォームをユーザーへ表示し、POST
ルートで新しいブログポストをデータベースへ保存します。The GET
route will
display a form for the user to create a new blog
post, while the POST
route will store
the new blog post in the database.
コントローラ作成Creating the Controller
次に、これらのルートへの受信リクエストを処理する単純なコントローラを見てみましょう。今のところ、store
メソッドは空のままにしておきます。Next, let's take a look at a
simple controller that handles incoming requests to
these routes. We'll leave the store
method empty for now:
<?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]);
}
}
バリデーションロジックWriting the Validation Logic
これで、新しいブログ投稿をバリデーションするロジックをstore
メソッドに入力する準備が整いました。これを行うには、Illuminate\Http\Request
オブジェクトが提供するvalidate
メソッドを使用します。バリデーションルールにパスすると、コードは正常に実行され続けます。しかし、バリデーションに失敗するとIlluminate\Validation\ValidationException
例外を投げ、適切なエラーレスポンスを自動的にユーザーへ返送します。Now we are ready to fill in our
store
method with the logic to validate
the new blog post. To do this, we will use the
validate
method provided by the
Illuminate\Http\Request
object. If the
validation rules pass, your code will keep executing
normally; however, if validation fails, an
Illuminate\Validation\ValidationException
exception will be thrown and the proper error
response will automatically be sent back to the
user.
伝統的なHTTPリクエスト処理中にバリデーションが失敗した場合、直前のURLへのリダイレクトレスポンスを生成します。受信リクエストがXHRリクエストの場合、バリデーションエラーメッセージを含むJSONレスポンスを返します。If validation fails during a traditional HTTP request, a redirect response to the previous URL will be generated. If the incoming request is an XHR request, a JSON response containing the validation error messages[#validation-error-response-format] will be returned.
validate
メソッドをもっとよく理解するため、store
メソッドに取り掛かりましょう。To get a better understanding of
the validate
method, let's jump back
into the store
method:
/**
* 新ブログポストの保存
*/
public function store(Request $request): RedirectResponse
{
$validated = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// ブログポストは有効
return redirect('/posts');
}
ご覧のとおり、バリデーションルールはvalidate
メソッドへ渡します。心配いりません。利用可能なすべてのバリデーションルールは文書化されています。この場合でもバリデーションが失敗したとき、適切な応答を自動的に生成します。バリデーションにパスすると、コントローラは正常に実行を継続します。As you can see, the validation
rules are passed into the validate
method. Don't worry - all available validation rules
are documented[#available-validation-rules].
Again, if the validation fails, the proper response
will automatically be generated. If the validation
passes, our controller will continue executing
normally.
もしくは、バリデーションルールを|
で区切る文字列の代わりに、ルールの配列で指定することもできます。Alternatively, validation rules
may be specified as arrays of rules instead of a
single |
delimited string:
$validatedData = $request->validate([
'title' => ['required', 'unique:posts', 'max:255'],
'body' => ['required'],
]);
さらに、validateWithBag
メソッドを使用して、リクエストをバリデーションした結果のエラーメッセージを名前付きエラーバッグ内へ保存できます。In addition, you may use the
validateWithBag
method to validate a
request and store any error messages within a
named error
bag[#named-error-bags]:
$validatedData = $request->validateWithBag('post', [
'title' => ['required', 'unique:posts', 'max:255'],
'body' => ['required'],
]);
最初のバリデーション失敗時に停止Stopping on First Validation Failure
最初のバリデーションに失敗したら、残りのバリデーションルールの判定を停止したい場合も、ときどき起きるでしょう。これには、bail
ルールを使ってください。Sometimes you may wish to stop
running validation rules on an attribute after the
first validation failure. To do so, assign the
bail
rule to the attribute:
$request->validate([
'title' => 'bail|required|unique:posts|max:255',
'body' => 'required',
]);
この例の場合、title
属性のunique
ルールに失敗すると、max
ルールをチェックしません。ルールは指定した順番にバリデートします。In this example, if the
unique
rule on the title
attribute fails, the max
rule will not
be checked. Rules will be validated in the order
they are assigned.
ネストした属性の注意点A Note on Nested Attributes
受信HTTPリクエストに「ネストされた」フィールドデータが含まれている場合は、「ドット」構文を使用してバリデーションルールでこうしたフィールドを指定できます。If the incoming HTTP request contains "nested" field data, you may specify these fields in your validation rules using "dot" syntax:
$request->validate([
'title' => 'required|unique:posts|max:255',
'author.name' => 'required',
'author.description' => 'required',
]);
フィールド名にピリオドそのものが含まれている場合は、そのピリオドをバックスラッシュでエスケープし、「ドット」構文として解釈されることを明示的に防げます。On the other hand, if your field name contains a literal period, you can explicitly prevent this from being interpreted as "dot" syntax by escaping the period with a backslash:
$request->validate([
'title' => 'required|unique:posts|max:255',
'v1\.0' => 'required',
]);
バリデーションエラー表示Displaying the Validation Errors
では、受信リクエストフィールドが指定したバリデーションルールにパスしない場合はどうなるでしょうか。前述のように、Laravelはユーザーを直前の場所へ自動的にリダイレクトします。さらに、すべてのバリデーションエラーとリクエスト入力は自動的にセッションに一時保持保存されます。So, what if the incoming request fields do not pass the given validation rules? As mentioned previously, Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors and request input[/docs/{{version}}/requests#retrieving-old-input] will automatically be flashed to the session[/docs/{{version}}/session#flash-data].
$errors
変数は、web
ミドルウェアグループが提供するIlluminate\View\Middleware\ShareErrorsFromSession
ミドルウェアにより、アプリケーションのすべてのビューで共有されます。このミドルウェアが適用されると、ビューで$errors
変数は常に定義され、$errors
変数が常に使用可能になり、安全・便利に使用できると想定できます。$errors
変数はIlluminate\Support\MessageBag
のインスタンスです。このオブジェクトの操作の詳細は、ドキュメントを確認してください。An $errors
variable
is shared with all of your application's views by
the
Illuminate\View\Middleware\ShareErrorsFromSession
middleware, which is provided by the
web
middleware group. When this
middleware is applied an $errors
variable will always be available in your views,
allowing you to conveniently assume the
$errors
variable is always defined and
can be safely used. The $errors
variable will be an instance of
Illuminate\Support\MessageBag
. For more
information on working with this object, check
out its
documentation[#working-with-error-messages].
この例では、バリデーションに失敗すると、エラーメッセージをビューで表示できるように、コントローラのcreate
メソッドへリダイレクトされることになります。So, in our example, the user will
be redirected to our controller's
create
method when validation fails,
allowing us to display the error messages in the
view:
<!-- /resources/views/post/create.blade.php -->
<h1>Create Post</h1>
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<!-- Postフォームの作成 -->
エラーメッセージのカスタマイズCustomizing the Error Messages
Laravelの組み込み検証ルールには、それぞれエラーメッセージがあり、アプリケーションのlang/en/validation.php
ファイル内に用意しています。アプリケーションにlang
ディレクトリがない場合は、lang:publish
Artisanコマンドにより、Laravelへ作成を指示してください。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.
lang/en/validation.php
ファイル内に、各バリデーションルールの翻訳エントリーがあります。これらのメッセージは、アプリケーションのニーズに応じて自由に変更・修正してください。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.
さらに、このファイルを他の言語ディレクトリにコピーして、アプリケーションように言語用メッセージを翻訳することもできます。Laravelの多言語化の詳細については、完全な多言語化のドキュメントをチェックしてみてください。In addition, you may copy this file to another language directory to translate the messages for your application's language. To learn more about Laravel localization, check out the complete localization documentation[/docs/{{version}}/localization].
Warning! Laravelアプリケーションのスケルトンは、デフォルトで
lang
ディレクトリを用意していません。Laravelの言語ファイルをカスタマイズしたい場合は、lang:publish
Artisanコマンドでリソース公開してください。[!WARNING]
By default, the Laravel application skeleton does not include thelang
directory. If you would like to customize Laravel's language files, you may publish them via thelang:publish
Artisan command.
XHRリクエストとバリデーションXHR Requests and Validation
この例では、従来のフォームを使用してデータをアプリケーションに送信しました。ただし、多くのアプリケーションは、JavaScriptを利用したフロントエンドから、XHRリクエストを受信します。XHRリクエスト中にvalidate
メソッドを使用すると、Laravelはリダイレクト応答を生成しません。代わりに、Laravelはすべてのバリデーションエラーを含むJSONレスポンスを生成します。このJSONレスポンスは、422
HTTPステータスコードとともに送信されます。In this
example, we used a traditional form to send data to
the application. However, many applications receive
XHR requests from a JavaScript powered frontend.
When using the validate
method during
an XHR request, Laravel will not generate a redirect
response. Instead, Laravel generates a JSON
response containing all of the validation
errors[#validation-error-response-format].
This JSON response will be sent with a 422 HTTP
status code.
@error
ディレクティブThe
@error
Directive
@error
Bladeディレクティブを使用して、特定の属性にバリデーションエラーメッセージが存在するかを簡単に判断できます。@error
ディレクティブ内で、$message
変数をエコーしてエラーメッセージを表示ができます。You may use the
@error
Blade[/docs/{{version}}/blade] directive to
quickly determine if validation error messages exist
for a given attribute. Within an @error
directive, you may echo the $message
variable to display the error message:
<!-- /resources/views/post/create.blade.php -->
<label for="title">Post 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
名前付きエラーバッグを使用している場合は、エラーバッグの名前を
@error
ディレクティブの第2引数へ渡せます。If you are using named error
bags[#named-error-bags], you may pass the
name of the error bag as the second argument to the
@error
directive:
<input ... class="@error('title', 'post') is-invalid @enderror">
フォームの再取得Repopulating Forms
Laravelがバリデーションエラーのためにリダイレクトレスポンスを生成するとき、フレームワークは自動的にセッションへのリクエストのすべての入力を一時保持保存します。これにより、直後のリクエスト時、保存しておいた入力に簡単にアクセスし、ユーザーが送信しようとしたフォームを再入力・再表示できるようにします。When Laravel generates a redirect response due to a validation error, the framework will automatically flash all of the request's input to the session[/docs/{{version}}/session#flash-data]. This is done so that you may conveniently access the input during the next request and repopulate the form that the user attempted to submit.
直前のリクエストから一時保持保存された入力を取得するには、Illuminate\Http\Request
のインスタンスでold
メソッドを呼び出します。old
メソッドは、直前に一時保持保存した入力データをセッションから取り出します。To retrieve flashed input from
the previous request, invoke the old
method on an instance of
Illuminate\Http\Request
. The
old
method will pull the previously
flashed input data from the
session[/docs/{{version}}/session]:
$title = $request->old('title');
Laravelはグローバルなold
ヘルパも提供しています。Bladeテンプレート内に古い入力を表示している場合は、old
ヘルパを使用してフォームを再入力・再表示する方が便利です。指定されたフィールドに古い入力が存在しない場合、null
が返されます。Laravel also provides a global
old
helper. If you are displaying old
input within a Blade
template[/docs/{{version}}/blade], it is
more convenient to use the old
helper
to repopulate the form. If no old input exists for
the given field, null
will be
returned:
<input type="text" name="title" value="{{ old('title') }}">
オプションフィールドに対する注意A Note on Optional Fields
Laravelはデフォルトで、TrimStrings
とConvertEmptyStringsToNull
ミドルウェアをアプリケーションのグローバルミドルウェアスタックに含めています。このため、バリデータにnull
値を無効と判定させたくない場合は、「オプション」のリクエストフィールドをnullable
としてマークする必要があります。一例を御覧ください。By default, Laravel includes the
TrimStrings
and
ConvertEmptyStringsToNull
middleware in
your application's global middleware stack. Because
of this, you will often need to mark your
"optional" request fields as
nullable
if you do not want the
validator to consider null
values as
invalid. For example:
$request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
'publish_at' => 'nullable|date',
]);
上記の例の場合、publish_at
フィールドがnull
か、有効な日付表現であることを指定しています。ルール定義にnullable
が追加されないと、バリデータはnull
を無効な日付として判定します。In this example, we are
specifying that the publish_at
field
may be either null
or a valid date
representation. If the nullable
modifier is not added to the rule definition, the
validator would consider null
an
invalid date.
バリデーションエラーのレスポンス形式Validation Error Response Format
受信HTTPリクエストがJSONレスポンスを期待しており、アプリケーションがIlluminate\Validation\ValidationException
例外を投げる場合、Laravelは自動的にエラーメッセージをフォーマットして、422
Unprocessable Entity
HTTPレスポンスを返します。When your application throws a
Illuminate\Validation\ValidationException
exception and the incoming HTTP request is expecting
a JSON response, Laravel will automatically format
the error messages for you and return a 422
Unprocessable Entity
HTTP
response.
以下に、バリデーションエラーのJSONレスポンスフォーマット例を示します。ネストしたエラーのキーは、「ドット」記法で1次元化されることに注意してください。Below, you can review an example of the JSON response format for validation errors. Note that nested error keys are flattened into "dot" notation format:
{
"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."
]
}
}
フォームリクエストバリデーションForm Request Validation
フォームリクエスト作成Creating Form Requests
より複雑なバリデーションシナリオの場合は、「フォームリクエスト」を作成することをお勧めします。フォームリクエストは、独自のバリデーションおよび認可ロジックをカプセル化するカスタムリクエストクラスです。フォームリクエストクラスを作成するには、make:request
Artisan CLIコマンドを使用します。For more
complex validation scenarios, you may wish to create
a "form request". Form requests are custom
request classes that encapsulate their own
validation and authorization logic. To create a form
request class, you may use the
make:request
Artisan CLI
command:
php artisan make:request StorePostRequest
生成するフォームリクエストクラスは、app/Http/Requests
ディレクトリに配置します。このディレクトリが存在しない場合は、make:request
コマンドの実行時に作成します。Laravelにが生成する各フォームリクエストには、authorize
とrules
の2つのメソッドがあります。The generated form request class
will be placed in the app/Http/Requests
directory. If this directory does not exist, it will
be created when you run the
make:request
command. Each form request
generated by Laravel has two methods:
authorize
and
rules
.
ご想像のとおり、authorize
メソッドは、現在認証されているユーザーがリクエストによって表されるアクションを実行できるかどうかを判断し、rules
メソッドはリクエスト中のデータを検証するバリデーションルールを返します。As you might have guessed, the
authorize
method is responsible for
determining if the currently authenticated user can
perform the action represented by the request, while
the rules
method returns the validation
rules that should apply to the request's
data:
/**
* リクエストに適用するバリデーションルールを取得
*
* @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
*/
public function rules(): array
{
return [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];
}
Note:
rules
メソッドの引数で必要な依存関係をタイプヒントにより指定できます。それらはLaravelサービスコンテナを介して自動的に依存解決されます。[!NOTE]
You may type-hint any dependencies you require within therules
method's signature. They will automatically be resolved via the Laravel service container[/docs/{{version}}/container].
では、どのようにバリデーションルールを実行するのでしょうか?必要なのはこのリクエストをコントローラのメソッドで、タイプヒントを使い指定することです。受信フォームリクエストは、コントローラメソッドを呼び出す前にバリデーションを行います。つまり、コントローラにバリデーションロジックを取っ散らかす必要はありません。So, how are the validation rules evaluated? All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic:
/**
* 新ブログポストの保存
*/
public function store(StorePostRequest $request): RedirectResponse
{
// 送信されたリクエストは正しい
// バリデーション済みデータの取得
$validated = $request->validated();
// バリデーション済み入力データの一部を取得
$validated = $request->safe()->only(['name', 'email']);
$validated = $request->safe()->except(['name', 'email']);
// ブログ投稿の保存処理…
return redirect('/posts');
}
バリデーションが失敗した場合、リダイレクトレスポンスを生成し、ユーザーを直前のページへ送り返します。エラーもセッションへ一時保存し、表示できるようにします。リクエストがXHRリクエストの場合、422ステータスコードで、バリデーションエラーのJSON表現を含むHTTPレスポンスがユーザーに返されます。If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an XHR request, an HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors[#validation-error-response-format].
Laravel Precognitionをチェックしてください。[!NOTE]
Note: Inertiaを搭載したLaravelのフロントエンドへ、リアルタイムのフォームリクエストバリデーションを追加する必要がありますか?
Need to add real-time form request validation to your Inertia powered Laravel frontend? Check out Laravel Precognition[/docs/{{version}}/precognition].
追加バリデーションの実行Performing Additional Validation
最初のバリデーションが完了した後に、追加のバリデーションを実行する必要がある場合があります。この場合、フォームリクエストのafter
メソッドを使用します。Sometimes you need to perform
additional validation after your initial validation
is complete. You can accomplish this using the form
request's after
method.
after
メソッドは、バリデーションが完了した後に呼び出すCallableやクロージャの配列を返す必要があります。指定Callablesは、Illuminate\Validation\Validator
インスタンスを受け取るので、必要に応じ追加のエラーメッセージを表示できます。The after
method
should return an array of callables or closures
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\Validation\Validator;
/**
* リクエストに対する「追加」バリデーションCallableの取得
*/
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
インスタンスを受け取ります。As noted, the array returned by
the after
method may also contain
invokable classes. The __invoke
method
of these classes will receive an
Illuminate\Validation\Validator
instance:
use App\Validation\ValidateShippingTime;
use App\Validation\ValidateUserStatus;
use Illuminate\Validation\Validator;
/**
* リクエストに対する「追加」バリデーションCallableの取得
*/
public function after(): array
{
return [
new ValidateUserStatus,
new ValidateShippingTime,
function (Validator $validator) {
//
}
];
}
バリデーションの最初の失敗で停止Stopping on the First Validation Failure
リクエストクラスにstopOnFirstFailure
プロパティを追加することで、バリデーションの失敗が起きてすぐに、すべての属性のバリデーションを停止する必要があることをバリデータへ指示できます。By adding a
stopOnFirstFailure
property to your
request class, you may inform the validator that it
should stop validating all attributes once a single
validation failure has occurred:
/**
* バリデータが最初のルールの失敗で停止するかを指示
*
* @var bool
*/
protected $stopOnFirstFailure = true;
リダイレクト先のカスタマイズCustomizing the Redirect Location
前述のとおり、フォームリクエストのバリデーションに失敗した場合、ユーザーを元の場所に戻すためにリダイレクトレスポンスが生成されます。しかし、この動作は自由にカスタマイズ可能です。それには、フォームのリクエストで、$redirect
プロパティを定義します。As previously discussed, a
redirect response will be generated to send the user
back to their previous location when form request
validation fails. However, you are free to customize
this behavior. To do so, define a
$redirect
property on your form
request:
/**
* バリデーション失敗時に、ユーザーをリダイレクトするURI
*
* @var string
*/
protected $redirect = '/dashboard';
または、ユーザーを名前付きルートへリダイレクトする場合は、$redirectRoute
プロパティを代わりに定義します。Or, if you would like to redirect
users to a named route, you may define a
$redirectRoute
property
instead:
/**
* バリデーション失敗時に、ユーザーをリダイレクトするルート
*
* @var string
*/
protected $redirectRoute = 'dashboard';
フォームリクエストの認可Authorizing Form Requests
フォームリクエストクラスには、authorize
メソッドも含まれています。このメソッド内で、認証済みユーザーが特定のリソースを更新する権限を持っているかどうかを判別できます。たとえば、ユーザーが更新しようとしているブログコメントを実際に所有しているかどうかを判断できます。ほとんどの場合、次の方法で認可ゲートとポリシーを操作します。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[/docs/{{version}}/authorization]
within this method:
use App\Models\Comment;
/**
* ユーザーがこのリクエストの権限を持っているかを判断する
*/
public function authorize(): bool
{
$comment = Comment::find($this->route('comment'));
return $comment && $this->user()->can('update', $comment);
}
全フォームリクエストはLaravelのベースリクエストクラスを拡張していますので、現在認証済みユーザーへアクセスする、user
メソッドが使えます。また、上記例中のroute
メソッドの呼び出しにも、注目してください。たとえば{comment}
パラメーターのような、呼び出しているルートで定義してあるURIパラメータにもアクセスできます。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[/docs/{{version}}/routing#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);
authorize
メソッドがfalse
を返すと、403ステータスコードのHTTPレスポンスを自動的に返し、コントローラメソッドは実行しません。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.
アプリケーションの別の部分でリクエストの認可ロジックを処理する場合は、authorize
メソッドを完全に削除し、true
を返してください。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
:
/**
* ユーザーがこのリクエストの権限を持っているかを判断する
*/
public function authorize(): bool
{
return true;
}
Note:
authorize
メソッドの引数で、必要な依存をタイプヒントにより指定できます。それらはLaravelのサービスコンテナにより、自動的に依存解決されます。[!NOTE]
You may type-hint any dependencies you need within theauthorize
method's signature. They will automatically be resolved via the Laravel service container[/docs/{{version}}/container].
エラーメッセージのカスタマイズCustomizing the Error Messages
フォームリクエストにより使用されているメッセージはmessage
メソッドをオーバーライドすることによりカスタマイズできます。このメソッドから属性/ルールと対応するエラーメッセージのペアを配列で返してください。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:
/**
* 定義済みバリデーションルールのエラーメッセージ取得
*
* @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
Laravelの組み込みバリデーションルールエラーメッセージの多くは、:attribute
プレースホルダーを含んでいます。バリデーションメッセージの:attribute
プレースホルダーをカスタム属性名に置き換えたい場合は、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:
/**
* バリデーションエラーのカスタム属性の取得
*
* @return array<string, string>
*/
public function attributes(): array
{
return [
'email' => 'email address',
];
}
バリデーションのための入力準備Preparing Input for Validation
バリデーションルールを適用する前にリクエストからのデータを準備またはサニタイズする必要がある場合は、prepareForValidation
メソッド使用します。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;
/**
* バリーデーションのためにデータを準備
*/
protected function prepareForValidation(): void
{
$this->merge([
'slug' => Str::slug($this->slug),
]);
}
同様に、バリデーションが完了した後にリクエストデータをノーマライズする必要がある場合は、
passedValidation
メソッドを使用します。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
リクエストのvalidate
メソッドを使用したくない場合は、Validator
ファサードを使用し、バリデータインスタンスを生成する必要があります。
このファサードのmake
メソッドで、新しいバリデータインスタンスを生成します。If you do not want to use the
validate
method on the request, you may
create a validator instance manually using the
Validator
facade[/docs/{{version}}/facades]. The
make
method on the facade generates a
new validator instance:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
/**
* 新しいブログポストの保存
*/
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();
}
// バリデーション済みデータの取得
$validated = $validator->validated();
// バリデーション済みデータの一部を取得
$validated = $validator->safe()->only(['name', 'email']);
$validated = $validator->safe()->except(['name', 'email']);
// ブログポストの保存処理…
return redirect('/posts');
}
}
make
メソッドの第1引数は、バリデーションを行うデータです。第2引数はそのデータに適用するバリデーションルールの配列です。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.
リクエストのバリデーションが失敗したかを判断した後、withErrors
メソッドを使用してエラーメッセージをセッションへ一時保持保存できます。この方法を使用すると、リダイレクト後に$errors
変数がビューで自動的に共有されるため、メッセージをユーザーへ簡単に表示できます。withErrors
メソッドは、バリデータ、MessageBag
、またはPHPのarray
を引数に取ります。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
stopOnFirstFailure
メソッドは、バリデーションが失敗したら、すぐにすべての属性のバリデーションを停止する必要があることをバリデータへ指示します。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
バリデータインスタンスを手作業で作成するが、HTTPリクエストのvalidate
メソッドによって提供される自動リダイレクトを利用したい場合は、既存のバリデータインスタンスでvalidate
メソッドを呼び出してください。バリデーションが失敗した場合、ユーザーは自動的にリダイレクトされます。XHRリクエストの場合は、JSONレスポンスが返されます。If you would like to create a
validator instance manually but still take advantage
of the automatic redirection offered by the HTTP
request's validate
method, you may call
the validate
method on an existing
validator instance. If validation fails, the user
will automatically be redirected or, in the case of
an XHR request, a JSON response will be
returned[#validation-error-response-format]:
Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
])->validate();
validateWithBag
メソッドを使用しリクエストのバリデートを行った結果、失敗した場合に、エラーメッセージを名前付きエラーバッグへ保存することもできます。You may use the
validateWithBag
method to store the
error messages in a named error
bag[#named-error-bags] if validation
fails:
Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
])->validateWithBag('post');
名前付きエラーバッグNamed Error Bags
1つのページに複数のフォームがある場合は、バリデーションエラーを含むMessageBag
に名前を付けて、特定のフォームのエラーメッセージを取得可能にできます。これを実現するには、withErrors
の2番目の引数として名前を渡します。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');
$errors
変数を使い、名前を付けたMessageBag
インスタンスへアクセスできます。You may then access the named
MessageBag
instance from the
$errors
variable:
{{ $errors->login->first('email') }}
エラーメッセージのカスタマイズCustomizing the Error Messages
必要に応じて、Laravelが提供するデフォルトのエラーメッセージの代わりにバリデータインスタンスが使用するカスタムエラーメッセージを指定できます。カスタムメッセージを指定する方法はいくつかあります。まず、カスタムメッセージをvalidator::make
メソッドに3番目の引数として渡す方法です。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.',
]);
この例の、:attribute
プレースホルダーは、バリデーション中のフィールドの名前に置き換えられます。バリデーションメッセージには他のプレースホルダーも利用できます。例をご覧ください。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
Laravelの組み込みエラーメッセージの多くは、バリデーション中のフィールドや属性の名前に置き換えられる:attribute
プレースホルダーを含んでいます。特定のフィールドでこれらのプレースホルダーを置き換える値をカスタマイズするには、カスタム属性表示名の配列を4番目の引数としてValidator::make
メソッドに渡します。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
最初のバリデーションが完了した後に、追加のバリデーションを実行する必要がある場合があります。バリデータのafter
メソッドで実現可能です。after
メソッドは、バリデーションが完了した後に呼び出すCallableやクロージャの配列を引数に取ります。指定Callablesは、Illuminate\Validation\Validator
インスタンスを受け取るので、必要に応じ追加のエラーメッセージを表示できます。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()) {
// ...
}
前述のとおり、after
メソッドは、呼び出し可能な配列を引数に取ります。「バリデーション後」のロジックが
実行可能なクラスへカプセル化されている場合は特に便利です。そのクラスは__invoke
メソッドで、Illuminate\Validation\Validator
インスタンスを受け取ります。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
フォームのリクエストや手作業で作成したバリデータのインスタンスを使って
リクエストデータをバリデーションした後に、バリデーション済みの受信リクエストデータを取得したいと思われるかもしれません。これには方法がいくつかあります。まず、フォームのリクエストやバリデータインスタンスのvalidated
メソッドを呼び出す方法です。このメソッドは、バリデーション済みデータの配列を返します。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();
または、フォームリクエストやバリデータのインスタンスに対して、safe
メソッドを呼び出すこともできます。このメソッドは、Illuminate\Support\ValidatedInput
のインスタンスを返します。このオブジェクトはonly
、except
、all
メソッドを用意しており、バリデーション済みデータのサブセットや配列全体を取得できます。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();
さらに、Illuminate\Support\ValidatedInput
インスタンスをループで配列のようにアクセスすることもできます。In addition, the
Illuminate\Support\ValidatedInput
instance may be iterated over and accessed like an
array:
// バリデーション済みデータをループ
foreach ($request->safe() as $key => $value) {
// ...
}
// バリデーション済みデータを配列としてアクセス
$validated = $request->safe();
$email = $validated['email'];
バリデーション済みデータへさらにフィールドを追加したい場合は、merge
メソッドを呼び出します。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']);
バリデーション済みデータをコレクションインスタンスとして取得したい場合は、collect
メソッドを呼び出します。If you would like to retrieve the
validated data as a
collection[/docs/{{version}}/collections]
instance, you may call the collect
method:
$collection = $request->safe()->collect();
エラーメッセージの操作Working With Error Messages
Validator
インスタンスのerrors
メソッドを呼び出すと、エラーメッセージを操作する便利なメソッドを数揃えた、Illuminate\Support\MessageBag
インスタンスを受け取れます。自動的に作成され、すべてのビューで使用できる$errors
変数も、MessageBag
クラスのインスタンスです。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
指定したフィールドの最初のエラーメッセージを取得するには、first
メソッドを使います。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 FieldRetrieving All Error Messages for a Field
指定したフィールドの全エラーメッセージを配列で取得したい場合は、get
メソッドを使います。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
全フィールドの全メッセージの配列を取得したい場合は、all
メソッドを使います。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
has
メソッドは、指定したフィールドのエラーメッセージが存在しているかを判定するために使います。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の組み込み検証ルールには、それぞれエラーメッセージがあり、アプリケーションのlang/en/validation.php
ファイル内に用意しています。アプリケーションにlang
ディレクトリがない場合は、lang:publish
Artisanコマンドにより、Laravelへ作成を指示してください。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.
lang/en/validation.php
ファイル内に、各バリデーションルールの翻訳エントリーがあります。これらのメッセージは、アプリケーションのニーズに応じて自由に変更・修正してください。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.
さらに、このファイルを他の言語ディレクトリにコピーして、アプリケーションように言語用メッセージを翻訳することもできます。Laravelの多言語化の詳細については、完全な多言語化のドキュメントをチェックしてみてください。In addition, you may copy this file to another language directory to translate the messages for your application's language. To learn more about Laravel localization, check out the complete localization documentation[/docs/{{version}}/localization].
Warning! Laravelアプリケーションのスケルトンは、デフォルトで
lang
ディレクトリを用意していません。Laravelの言語ファイルをカスタマイズしたい場合は、lang:publish
Artisanコマンドでリソース公開してください。[!WARNING]
By default, the Laravel application skeleton does not include thelang
directory. If you would like to customize Laravel's language files, you may publish them via thelang:publish
Artisan command.
特定の属性のカスタムメッセージCustom Messages for Specific Attributes
アプリケーションのバリデーション言語ファイルでは、特定の属性とルールの組み合わせで使用するエラーメッセージをカスタマイズできます。これを行うには、アプリケーションのlang/xx/validation.php
言語ファイルのcustom
配列に、カスタマイズメッセージを追加します。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
Laravelの組み込みエラーメッセージの多くは、:attribute
プレースホルダーを含んでおり、バリデーション中のフィールドや属性の名前に置き換えます。もし、バリデーションメッセージの:attribute
部分をカスタム値に置き換えたい場合は、言語ファイルlang/xx/validation.php
のattributes
配列でカスタム属性名を指定できます。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! Laravelアプリケーションのスケルトンは、デフォルトで
lang
ディレクトリを用意していません。Laravelの言語ファイルをカスタマイズしたい場合は、lang:publish
Artisanコマンドでリソース公開してください。[!WARNING]
By default, the Laravel application skeleton does not include thelang
directory. If you would like to customize Laravel's language files, you may publish them via thelang:publish
Artisan command.
言語ファイルでの値の指定Specifying Values in Language Files
Laravelの組み込みバリデーションルールエラーメッセージの一部は、リクエスト属性の現在の値に置き換えられる:value
プレースホルダーを含んでいます。しかし、バリデーションメッセージの:value
部分を値のカスタム表現へ置き換えたい場合があるでしょう。たとえば、payment_type
の値がcc
の場合にクレジットカード番号が必要であることを定義する次のルールについて考えてみます。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.
支払タイプの値にcc
と表示する代わりに、lang/xx/validation.php
言語ファイルでvalues
配列を定義し、よりユーザーフレンドリーな値表現を指定できます。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! Laravelアプリケーションのスケルトンは、デフォルトで
lang
ディレクトリを用意していません。Laravelの言語ファイルをカスタマイズしたい場合は、lang:publish
Artisanコマンドでリソース公開してください。[!WARNING]
By default, the Laravel application skeleton does not include thelang
directory. If you would like to customize Laravel's language files, you may publish them via thelang: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:
受け入れ 条件一致時受け入れ アクティブなURL (日付)より後 (日付)以降 アルファベット アルファベット記号 アルファベット数字 配列 Ascii 継続終了 (日付)より前 (日付)以前 範囲 論理 確認 現在のパスワード 日付 同一日付 日付形式 小数点以下 拒否 条件一致時拒否 相違 桁指定数値 桁範囲指定数値 寸法(画像ファイル) 別々 文字列非開始 文字列非終了 メールアドレス 文字列終了 列挙型 除外 条件一致時フィールド除外 条件不一致時フィールド除外 存在時フィールド除外 不在時フィールド除外 存在(データベース) 拡張子 ファイル 充満 より大きい 以上 Hex Color 画像(ファイル) 内包 配列内 整数 IPアドレス JSON より小さい 以下 リスト 小文字 MACアドレス 最大値 最大桁数 MIMEタイプ MIMEタイプ(ファイル拡張子) 最小値 最小桁数 非入力 条件一致時非入力 条件不一致時非入力 存在時非入力 全不在時非入力 倍数値 非内包 正規表現不一致 NULL許可 数値 存在 条件一致時存在 条件非一致時存在 存在時存在 全存在時存在 禁止 条件一致時禁止 条件不一致時禁止 他フィールド禁止 正規表現 必須 指定フィールド値一致時必須 受け入れ時必須 指定フィールド値非一致時必須 指定フィールド存在時必須 全指定フィールド存在時必須 指定フィールド非存在時必須 全指定フィールド非存在時必須 配列かつキー包含必須 同一 サイズ 存在時バリデート実行 文字列開始 文字列 タイムゾーン 一意(データベース) 大文字 URL ULID UUID
acceptedaccepted
フィールドが、"yes"
、"on"
、1
、"1"
、true
、"true"
であることをバリデートします。これは、「利用規約」の承認または同様のフィールドをバリデーションするのに役立ちます。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:他のフィールド,値,...accepted_if:anotherfield,value,...
他のフィールドが指定した値と等しい場合、このフィールドは
"yes"
、"on"
、1
、"1"
、"true"
、true
であることをバリデートします。これは、「利用規則」の了承や似たようなフィールドをバリデートするのに便利です。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_urlactive_url
フィールドが、dns_get_record
PHP関数により、有効なAかAAAAレコードであることをバリデートします。dns_get_record
へ渡す前に、parse_url
PHP関数により指定した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:日付after:date
フィールドは、指定された日付以降の値であることをバリデートします。日付を有効なDateTime
インスタンスに変換するため、strtotime
PHP関数に渡します。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'
strtotime
により評価される日付文字列を渡す代わりに、その日付と比較する他のフィールドを指定することもできます。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'
after_or_equal:日付after_or_equal:date
フィールドが指定した日付以降であることをバリデートします。詳細はafterルールを参照してください。The field under validation must be a value after or equal to the given date. For more information, see the after[#rule-after] rule.
alphaalpha
フィールドは、\p{L}
、並びに\p{M}
に含まれる、Unicodeのアルファベット文字のみであることをバリデートします。The field under validation must
be entirely Unicode alphabetic characters contained
in
\p{L}
[https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=[:L:]&g=&i=]
and
\p{M}
[https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=[:M:]&g=&i=].
このバリデーションルールをASCII文字(a-z
とA-Z
)の範囲に限定したい場合は、ascii
オプションを指定してください。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_dashalpha_dash
フィールドは、\p{L}
、並びに\p{M}
、\p{N}
に含まれる、Unicodeのアルファベット文字と数字、およびASCIIのダッシュ(-
)とASCIIの下線(_
)であることをバリデートします。The field under validation must
be entirely Unicode alpha-numeric characters
contained in
\p{L}
[https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=[:L:]&g=&i=],
\p{M}
[https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=[:M:]&g=&i=],
\p{N}
[https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=[:N:]&g=&i=],
as well as ASCII dashes (-
) and ASCII
underscores (_
).
このバリデーションルールをASCII文字(a-z
とA-Z
)の範囲に限定したい場合は、ascii
オプションを指定してください。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_dash:ascii',
alpha_numalpha_num
フィールドは、\p{L}
、並びに\p{M}
、\p{N}
に含まれる、Unicodeのアルファベット文字と数字のみであることをバリデートします。The field under validation must
be entirely Unicode alpha-numeric characters
contained in
\p{L}
[https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=[:L:]&g=&i=],
\p{M}
[https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=[:M:]&g=&i=],
and
\p{N}
[https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=[:N:]&g=&i=].
このバリデーションルールをASCII文字(a-z
とA-Z
)の範囲に限定したい場合は、ascii
オプションを指定してください。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_num:ascii',
arrayarray
フィールドがPHPの配列タイプであることをバリデートします。The field under validation must
be a PHP array
.
array
ルールに追加の値を指定する場合、入力配列の各キーは、ルールに指定した値のリスト内に存在する必要があります。次の例では、入力配列のadmin
キーは、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.
asciiascii
フィールドが全て7ビットのアスキー文字であることをバリデートします。The field under validation must be entirely 7-bit ASCII characters.
bailbail
フィールドでバリデーションにはじめて失敗した時点で、残りのルールのバリデーションを中止します。Stop running validation rules for the field after the first validation failure.
bail
ルールはバリデーションが失敗したときに、特定のフィールドのバリデーションのみを停止するだけで、一方のstopOnFirstFailure
メソッドは、ひとつバリデーション失敗が発生したら、すべての属性のバリデーションを停止する必要があることをバリデータに指示します。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:日付before:date
フィールドは、指定された日付より前の値であることをバリデートします。日付を有効なDateTime
インスタンスへ変換するために、PHPのstrtotime
関数へ渡します。さらに、after
ルールと同様に、バリデーション中の別のフィールドの名前を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
.
before_or_equal:日付before_or_equal:date
フィールドは、指定された日付より前または同じ値であることをバリデートします。日付を有効なDateTime
インスタンスへ変換するために、PHPのstrtotime
関数へ渡します。さらに、after
ルールと同様に、バリデーション中の別のフィールドの名前を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
.
between:min,maxbetween:min,max
フィールドが指定した最小値以上で、最大値以下のサイズであることをバリデートします。size
ルールと同様の判定方法で、文字列、数値、配列、ファイルが評価されます。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.
booleanboolean
フィールドが論理値として有効であることをバリデートします。受け入れられる入力は、true
、false
、1
、0
、"1"
、"0"
です。The field under validation must
be able to be cast as a boolean. Accepted input are
true
, false
,
1
, 0
,
"1"
, and
"0"
.
confirmedconfirmed
フィールドが、{field}_confirmation
フィールドと一致する必要があります。たとえば、バリデーション中のフィールドが「password」の場合、「password_confirmation」フィールドが入力に存在し一致している必要があります。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.
current_passwordcurrent_password
フィールドが、認証されているユーザーのパスワードと一致することをバリデートします。ルールの最初のパラメータで、認証ガードを指定できます。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'
datedate
パリデーションされる値はPHP関数のstrtotime
により有効であり、相対日付ではないことをバリデートします。The field under validation must
be a valid, non-relative date according to the
strtotime
PHP function.
date_equals:日付date_equals:date
フィールドが、指定した日付と同じことをバリデートします。日付を有効なDateTime
インスタンスに変換するために、PHPのstrtotime
関数へ渡します。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:フォーマット,…date_format:format,...
バリデーションされる値が、指定するフォーマット定義のどれか一つと一致するかバリデートします。バリデーション時にはdate
かdate_format
のどちらかを使用しなくてはならず、両方はできません。このバリデーションはPHPのDateTimeクラスがサポートするフォーマットをすべてサポートしています。The field under validation must
match one of the given formats. You should
use either date
or
date_format
when validating a field,
not both. This validation rule supports all formats
supported by PHP's
DateTime[https://www.php.net/manual/en/class.datetime.php]
class.
decimal:min,maxdecimal:min,max
フィールドが数値であり、指定された小数点以下の桁数を含んでいることをバリデートします。The field under validation must be numeric and must contain the specified number of decimal places:
// 小数点以下が2桁ピッタリの必要がある(9.99)
'price' => 'decimal:2'
// 小数点以下が2から4桁である必要がある
'price' => 'decimal:2,4'
declineddeclined
The field under validation must be
"no"
,
"off"
, 0
,
"0"
, false
, or
"false"
.The field under validation must
be "no"
,
"off"
, 0
,
"0"
, false
, or
"false"
.
declined_if:他のフィールド,値,...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.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:フィールドdifferent:field
フィールドが指定されたフィールドと異なった値を指定されていることをバリデートします。The field under validation must have a different value than field.
digits:値digits:value
フィールドが整数で、値の桁数であることをバリデートします。The integer under validation must have an exact length of value.
digits_between:最小値,最大値digits_between:min,max
フィールドが整数で、桁数が最小値から最大値の間であることをバリデートします。The integer validation must have a length between the given min and max.
dimensionsdimensions
バリデーション対象のファイルが、パラメータにより指定されたサイズに合致することをバリデートします。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'
使用可能なパラメータは、min_width、max_width、min_height、max_height、width、height、ratioです。Available constraints are: min_width, max_width, min_height, max_height, width, height, ratio.
*ratio*制約は、幅を高さで割ったものとして表す必要があります。これは、3/2
のような分数または1.5
のようなfloatのいずれかで指定します。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'
このルールは多くの引数を要求するので、Rule::dimensions
メソッドを使い、記述的にこのルールを構築してください。Since this rule requires several
arguments, you may 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),
],
]);
distinctdistinct
配列のバリデーション時、フィールドに重複した値がないことをバリデートします。When validating arrays, the field under validation must not have any duplicate values:
'foo.*.id' => 'distinct'
distinctはデフォルトで緩い比較を使用します。厳密な比較を使用するには、検証ルール定義にstrict
パラメータを追加することができます。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'
バリデーションルールの引数にignore_case
を追加して、大文字と小文字の違いを無視するルールを加えられます。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,...doesnt_start_with:foo,bar,...
フィールドの値が指定した値で開始しないことをバリデートします。The field under validation must not start with one of the given values.
doesnt_end_with:foo,bar,...doesnt_end_with:foo,bar,...
フィールドの値が指定した値で終了しないことをバリデートします。The field under validation must not end with one of the given values.
emailemail
バリデーション中のフィールドは、電子メールアドレスのフォーマットである必要があります。このバリデーションルールは、egulias/email-validator
パッケージを使用して電子メールアドレスをバリデーションします。デフォルトではRFCValidation
バリデータが適用されますが、他のバリデーションスタイルを適用することもできます。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'
上記の例では、RFCValidation
とDNSCheckValidation
バリデーションを適用しています。適用可能なバリデーションスタイルは、次の通りです。The example above will apply the
RFCValidation
and
DNSCheckValidation
validations. Here's
a full list of validation styles you can
apply:
rfc
:RFCValidation
rfc
:RFCValidation
strict
:NoRFCWarningsValidation
strict
:NoRFCWarningsValidation
dns
:DNSCheckValidation
dns
:DNSCheckValidation
spoof
:SpoofCheckValidation
spoof
:SpoofCheckValidation
filter
:FilterEmailValidation
filter
:FilterEmailValidation
filter_unicode
:FilterEmailValidation::unicode()
filter_unicode
:FilterEmailValidation::unicode()
PHPのfilter_var
関数を使用するfilter
バリデータは、Laravelに付属しており、Laravelバージョン5.8より前のLaravelのデフォルトの電子メールバリデーション動作でした。The
filter
validator, which uses PHP's
filter_var
function, ships with Laravel
and was Laravel's default
email validation behavior
prior to Laravel version
5.8.
Warning!
dns
およびspoof
バリデータには、PHPのintl
拡張が必要です。[!WARNING]
Thedns
andspoof
validators require the PHPintl
extension.
ends_with:foo,bar,...ends_with:foo,bar,...
フィールドの値が、指定された値で終わることをバリデートします。The field under validation must end with one of the given values.
enumenum
Enum
ルールはクラスベースのルールで、対象のフィールドに有効なenumの値が含まれているかどうかをバリデートします。Enum
ルールは、コンストラクタの引数に唯一、enumの名前を取ります。プリミティブ値のバリデーションを行う際は、Enum
ルールに値に依存した(backed)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)],
]);
Enum
ルールのonly
メソッドとexcept
メソッドを使用し、有効な列挙ケースを制限できます。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]);
when
メソッドは、Enum
ルールを条件付きで変更するために使います。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(...),
);
excludeexclude
フィルードの値がvalidate
とvalidated
メソッドが返すリクエストデータから除外されていることをバリデートします。The field
under validation will be
excluded from the request
data returned by the
validate
and
validated
methods.
exclude_if:他のフィールド,値exclude_if:anotherfield,value
他のフィールドが値と等しい場合、validate
とvalidated
メソッドが返すリクエストデータから、バリデーション指定下のフィールドが除外されます。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.
複雑な条件付き除外ロジックが必要な場合は、Rule::excludeIf
メソッドが便利です。このメソッドは、論理値かクロージャを引数に取ります。クロージャを指定する場合、そのクロージャは、true
またはfalse
を返し、バリデーション中のフィールドを除外するかしないかを示す必要があります。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:他のフィールド,値exclude_unless:anotherfield,value
他のフィールドが値と等しくない場合、validate
とvalidated
メソッドが返すリクエストデータから、バリデーション指定下のフィールドが除外されます。もし値がnull
(exclude_unless:name,null
)の場合は、比較フィールドがnull
であるか、比較フィールドがリクエストデータに含まれていない限り、バリデーション指定下のフィールドは除外されます。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.
exclude_with:他のフィールドexclude_with:anotherfield
他のフィールドが存在する場合、validate
とvalidated
メソッドが返すリクエストデータから、バリデーション指定可のフィールドが除外されます。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:他のフィールドexclude_without:anotherfield
他のフィールドが存在しない場合、validate
とvalidated
メソッドが返すリクエストデータから、バリデーション指定下のフィールドが除外されます。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:テーブル,カラムexists:table,column
フィールドは、指定のデータベーステーブルに存在する必要があります。The field under validation must exist in a given database table.
基本的なExistsルールの使用法Basic Usage of Exists Rule
'state' => 'exists:states'
column
オプションが指定されていない場合、フィールド名が使用されます。したがって、この場合、ルールは、states
データベーステーブルに、リクエストのstate
属性値と一致するstate
カラム値を持つレコードが含まれていることをバリデーションします。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'
場合によっては、exists
クエリに使用する特定のデータベース接続を指定する必要があります。これは、接続名をテーブル名の前に付けることで実現できます。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'
テーブル名を直接指定する代わりに、Eloquentモデルを指定することもできます。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'
バリデーションルールで実行されるクエリをカスタマイズしたい場合は、ルールをスムーズに定義できるRule
クラスを使ってください。下の例では、|
文字を区切りとして使用する代わりに、バリデーションルールを配列として指定しています。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;
Validator::make($data, [
'email' => [
'required',
Rule::exists('staff')->where(function (Builder $query) {
return $query->where('account_id', 1);
}),
],
]);
Rule::exists
メソッドが生成する、exists
ルールで使用するデータベースカラム名は、exists
メソッドの第2引数として明示的に指定できます。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'),
extensions:foo,bar,...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! ユーザーが割り当てた拡張子だけでファイルをバリデートしてはいけません。このルールは通常、
mimes
またはmimetypes
ルールと組み合わせて使用する必要があります。[!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 themimes
[#rule-mimes] ormimetypes
[#rule-mimetypes] rules.
filefile
フィールドがアップロードに成功したファイルであることをバリデートします。The field under validation must be a successfully uploaded file.
filledfilled
フィールドが存在する場合、空でないことをバリデートします。The field under validation must not be empty when it is present.
gt:fieldgt:field
フィールドが指定したフィールドか値より大きいことをバリデートします。2つのフィールドは同じタイプでなくてはなりません。文字列、数値、配列、ファイルは、size
ルールと同じ規約により評価します。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:fieldgte:field
フィールドが指定したフィールドか値以上であることをバリデートします。2つのフィールドは同じタイプでなくてはなりません。文字列、数値、配列、ファイルは、size
ルールと同じ規約により評価します。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_colorhex_color
フィールドが、16進数形式の有効な色値を含んでいることをバリデートします。The field under validation must contain a valid color value in hexadecimal[https://developer.mozilla.org/en-US/docs/Web/CSS/hex-color] format.
imageimage
ファイルは画像(jpg、jpeg、png、bmp、gif、svg、webp)であることをバリデートします。The file under validation must be an image (jpg, jpeg, png, bmp, gif, svg, or webp).
in:foo,bar...in:foo,bar,...
フィールドが指定したリストの中の値に含まれていることをバリデートします。このルールを使用するために配列をimplode
する必要が多くなりますので、ルールを記述的に構築するには、Rule::in
メソッドを使ってください。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']),
],
]);
in
ルールとarray
ルールを組み合わせた場合、入力配列の各値は、in
ルールに指定した値のリスト内に存在しなければなりません。次の例では,入力配列中のLAS
空港コードは,in
ルールへ指定した空港のリストに含まれていないため無効です。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:他のフィールド.*in_array:anotherfield.*
フィールドが、他のフィールドの値のどれかであることをバリデートします。The field under validation must exist in anotherfield's values.
integerinteger
フィールドが整数値であることをバリデートします。The field under validation must be an integer.
Warning! このバリデーションルールは、入力が「整数」変数タイプであるかを確認しません。入力がPHPの
FILTER_VALIDATE_INT
ルールで受け入れられるかバリデーションするだけです。入力を数値としてバリデーションする必要がある場合は、このルールをnumeric
バリデーションルールと組み合わせて使用してください。[!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'sFILTER_VALIDATE_INT
rule. If you need to validate the input as being a number please use this rule in combination with thenumeric
validation rule[#rule-numeric].
ipip
フィールドがIPアドレスの形式として正しいことをバリデートします。The field under validation must be an IP address.
ipv4ipv4
フィールドがIPv4アドレスの形式として正しいことをバリデートします。The field under validation must be an IPv4 address.
ipv6ipv6
フィールドがIPv6アドレスの形式として正しいことをバリデートします。The field under validation must be an IPv6 address.
jsonjson
フィールドが有効なJSON文字列であることをバリデートします。The field under validation must be a valid JSON string.
lt:fieldlt:field
フィールドが指定したフィールドより小さいことをバリデートします。2つのフィールドは同じタイプでなくてはなりません。文字列、数値、配列、ファイルは、size
ルールと同じ規約により評価します。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:fieldlte:field
フィールドが指定したフィールド以下であることをバリデートします。2つのフィールドは同じタイプでなくてはなりません。文字列、数値、配列、ファイルは、size
ルールと同じ規約により評価します。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.
lowercaselowercase
フィールドが小文字であることをバリデートします。The field under validation must be lowercase.
listlist
フィールドが、リストの配列であることをバリデートします。配列は、キーが0からcount($array)
-
1
までの連続した数値で構成されている場合、リストとみなします。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_addressmac_address
フィールドがMACアドレスとして正しいことをバリデートします。The field under validation must be a MAC address.
max:値max:value
フィールドが最大値として指定された値以下であることをバリデートします。size
ルールと同様の判定方法で、文字列、数値、配列、ファイルが評価されます。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:値max_digits:value
整数フィールドが、最大値桁数以下であることをバリデートします。The integer under validation must have a maximum length of value.
mimetypes:text/plain,...mimetypes:text/plain,...
フィールドが指定するMIMEタイプのどれかであることをバリデートします。The file under validation must match one of the given MIME types:
'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime'
アップロードしたファイルのMIMEタイプを判別するために、ファイルの内容が読み取られ、フレームワークはMIMEタイプを推測します。これは、クライアントが提供するMIMEタイプとは異なる場合があります。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,...mimes:foo,bar,...
ファイルは、リストする拡張子のいずれかに対応するMIMEタイプを持っていることをバリデートします。The file under validation must have a MIME type corresponding to one of the listed extensions:
'photo' => 'mimes:jpg,bmp,png'
拡張子を指定するだけでもよいのですが、このルールは実際には、ファイルの内容を読み取ってそのMIMEタイプを推測することにより、ファイルのMIMEタイプをバリデーションします。MIMEタイプとそれに対応する拡張子の完全なリストは、次の場所にあります。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:
https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
MIMEタイプと拡張子MIME Types and Extensions
このバリデーションルールは、MIMEタイプとユーザーがファイルに割り当てた拡張子との一致をバリデートするものではありません。例えば、mimes:png
バリデーションルールは、ファイル名がphoto.txt
であっても、有効なPNGコンテンツを含むファイルを有効なPNG画像とみなします。ユーザーがファイルへ割り当てた拡張子をバリデートしたい場合は、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.
min:値min:value
フィールドが最小値として指定された値以上であることをバリデートします。size
ルールと同様の判定方法で、文字列、数値、配列、ファイルが評価されます。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:値min_digits:value
整数フィールドが、最小値桁数以上であることをバリデートします。The integer under validation must have a minimum length of value.
multiple_of:値multiple_of:value
フィールドが、値の倍数であることをバリデートします。The field under validation must be a multiple of value.
missingmissing
フィールドが入力データ中に存在しないことをバリデートします。The field under validation must not be present in the input data.
missing_if:他のフィールド,値,...missing_if:anotherfield,value,...
他のフィールドが値のどれかと等しい場合、フィールドが入力データ中に存在しないことをバリデートします。The field under validation must not be present if the anotherfield field is equal to any value.
missing_unless:他のフィールド,値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,...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,...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,...not_in:foo,bar,...
フィールドが指定された値のリスト中に含まれていないことをバリデートします。Rule::notIn
メソッドのほうが、ルールの構成が読み書きしやすいでしょう。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:正規表現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'
.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!
regex
/not_regex
パターンを使用するとき、特に正規表現に|
文字が含まれている場合は、|
区切り文字を使用する代わりに配列を使用してバリデーションルールを指定する必要があります。[!WARNING]
When using theregex
/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.
nullablenullable
フィールドがnull
値であることを許容します。The field
under validation may be
null
.
numericnumeric
フィールドは数値であることをバリデートします。The field under validation must be numeric[https://www.php.net/manual/en/function.is-numeric.php].
presentpresent
フィールドが入力データに存在していることをバリデートします。The field under validation must exist in the input data.
present_if:他フィールド,値,…present_if:anotherfield,value,...
他フィールドが値のどれかに等しい場合、フィールドが存在することをバリデートします。The field under validation must be present if the anotherfield field is equal to any value.
present_unless:他フィールド,値present_unless:anotherfield,value
他フィールドがvalueのいずれにも等しくない場合、フィールドが存在することをバリデートします。The field under validation must be present unless the anotherfield field is equal to any value.
present_with:foo,bar,...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,...present_with_all:foo,bar,...
指定する他のフィールドすべてがが存在する場合のみ、フィールドが存在することをバリデートします。The field under validation must be present only if all of the other specified fields are present.
prohibitedprohibited
フィールドが存在しないか、または空であることをバリデートします。フィールドが以下の条件のいずれかである場合、「空」であると判定します。The field under validation must be missing or empty. A field is "empty" if it meets one of the following criteria:
- 値が
null
である。The value isnull
. - 値が空文字列である。The value is an empty string.
- 値が空配列であるか、空の
Countable
オブジェクトである。The value is an empty array or emptyCountable
object. - 値がパスのないアップロード済みファイルである。The value is an uploaded file with an empty path.
prohibited_if:他のフィールド,値,…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:
- 値が
null
である。The value isnull
. - 値が空文字列である。The value is an empty string.
- 値が空配列であるか、空の
Countable
オブジェクトである。The value is an empty array or emptyCountable
object. - 値がパスのないアップロード済みファイルである。The value is an uploaded file with an empty path.
複雑な条件付き禁止(空か存在してない)ロジックが必要な場合は、Rule::prohibitedIf
メソッドを利用してください。このメソッドは、論理値かクロージャを引数に取ります。クロージャを指定する場合、そのクロージャはtrue
またはfalse
を返し、バリデーション中のフィールドを禁止するかしないかを示す必要があります。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_unless:他のフィールド,値,…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:
- 値が
null
である。The value isnull
. - 値が空文字列である。The value is an empty string.
- 値が空配列であるか、空の
Countable
オブジェクトである。The value is an empty array or emptyCountable
object. - 値がパスのないアップロード済みファイルである。The value is an uploaded file with an empty path.
prohibits:他のフィールド,…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:
- 値が
null
である。The value isnull
. - 値が空文字列である。The value is an empty string.
- 値が空配列であるか、空の
Countable
オブジェクトである。The value is an empty array or emptyCountable
object. - 値がパスのないアップロード済みファイルである。The value is an uploaded file with an empty path.
regex:正規表現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'
.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!
regex
/not_regex
パターンを使用するとき、特に正規表現に|
文字が含まれている場合は、|
区切り文字を使用する代わりに、配列でルールを指定する必要があります。[!WARNING]
When using theregex
/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.
requiredrequired
フィールドが入力データ中に存在し、かつ空でないことをバリデートします。フィールドが以下の条件のいずれかの場合、そのフィールドを「空」であると判定します。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:
- 値が
null
である。The value isnull
. - 値が空文字列である。The value is an empty string.
- 値が空配列であるか、空の
Countable
オブジェクトである。The value is an empty array or emptyCountable
object. - 値がパスのないアップロード済みファイルである。The value is an uploaded file with no path.
required_if:他のフィールド,値,...required_if:anotherfield,value,...
他のフィールドが値のどれかと一致している場合、このフィールドが存在し、かつ空でないことをバリデートします。The field under validation must be present and not empty if the anotherfield field is equal to any value.
required_if
ルールのより複雑な条件を作成したい場合は、Rule::requiredIf
メソッドを使用できます。このメソッドは、ブール値またはクロージャを受け入れます。クロージャが渡されると、クロージャは「true」または「false」を返し、バリデーション中のフィールドが必要かどうかを示します。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:他のフィールド,...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"
.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_unless:他のフィールド,値,...required_unless:anotherfield,value,...
他のフィールドが値のどれとも一致していない場合、このフィールドが存在し、かつ空でないことをバリデートします。これは値がnull
でない限り、他のフィールドはリクエストデータに存在しなければならないという意味でもあります。もし値がnull
(required_unless:name,null
)の場合は、比較フィールドがnull
であるか、リクエストデータに比較フィールドが存在しない限り、バリデーション対象下のフィールドは必須です。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.
required_with:foo,bar,...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,...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,...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,...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,...required_array_keys:foo,bar,...
フィールドは配列であり、少なくとも指定したキーを含んでいることをバリデートします。The field under validation must be an array and must contain at least the specified keys.
same:フィールドsame:field
フィールドが、指定したフィールドと同じ値であることをバリデートします。The given field must match the field under validation.
size:値size:value
フィールドは指定した値と同じサイズであることをバリデートします。文字列の場合、値は文字長です。数値項目の場合、値は整数値(属性にnumeric
かinteger
ルールを持っている必要があります)です。配列の場合、値は配列の個数(count
)です。ファイルの場合、値はキロバイトのサイズです。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:
// 文字列長が12文字ちょうどであることをバリデートする
'title' => 'size:12';
// 指定された整数が10であることをバリデートする
'seats' => 'integer|size:10';
// 配列にちょうど5要素あることをバリデートする
'tags' => 'array|size:5';
// アップロードしたファイルが512キロバイトぴったりであることをバリデートする
'image' => 'file|size:512';
starts_with:foo,bar,...starts_with:foo,bar,...
フィールドが、指定した値のどれかで始まることをバリデートします。The field under validation must start with one of the given values.
stringstring
フィルードは文字列タイプであることをバリデートします。フィールドがnull
であることも許す場合は、そのフィールドにnullable
ルールも指定してください。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.
timezonetimezone
The
field
under
validation
must
be
a
valid
timezone
identifier
according
to
the
DateTimeZone::listIdentifiers
method.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: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';
'timezone' => 'required|timezone:Africa';
'timezone' => 'required|timezone:per_country,US';
unique:テーブル,カラムunique:table,column
フィールドが、指定されたデータベーステーブルに存在しないことをバリデートします。The field under validation must not exist within the given database table.
カスタムテーブル/カラム名の指定Specifying a Custom Table / Column Name:
テーブル名を直接指定する代わりに、Eloquentモデルを指定することもできます。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'
column
オプションは、フィールドの対応するデータベースカラムを指定するために使用します。column
オプションが指定されていない場合、バリデーション中のフィールドの名前が使用されます。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'
指定されたIDのuniqueルールを無視するForcing a Unique Rule to Ignore a Given ID:
場合により、uniqueのバリデーション中に特定の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.
バリデータにユーザーIDを無視するように指示するには、ルールをスムーズに定義できるRule
クラスを使います。以下の例の場合、さらにルールを|
文字を区切りとして使用する代わりに、バリデーションルールを配列として指定しています。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;
Validator::make($data, [
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
]);
Warning! ユーザーがコントロールするリクエストの入力を
ignore
メソッドへ、決して渡してはいけません。代わりに、Eloquentモデルインスタンスの自動増分IDやUUIDのような、生成されたユニークなIDだけを渡してください。そうしなければ、アプリケーションがSQLインジェクション攻撃に対し、脆弱になります。[!WARNING]
You should never pass any user controlled request input into theignore
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.
モデルキーの値をignore
メソッドに渡す代わりに、モデルインスタンス全体を渡すこともできます。Laravelはモデルからキーを自動的に抽出します: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)
もし、テーブルの主キーとしてid
以外のカラム名を使用している場合は、ignore
メソッドを呼び出す時に、カラムの名前を指定してください。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')
unique
ルールはデフォルトで、バリデートしようとしている属性名と一致するカラムの同一性をチェックします。しかしながら、unique
メソッドの第2引数として、異なったカラム名を渡すことも可能です。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)
追加のWHERE節を付け加えるAdding Additional Where Clauses:
where
メソッドを使用してクエリをカスタマイズすることにより、追加のクエリ条件を指定できます。たとえば、account_id
列の値が1
の検索レコードのみ検索するクエリ条件で絞り込むクエリを追加してみます。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))
uppercaseuppercase
フィールドが大文字であることをバリデートします。The field under validation must be uppercase.
urlurl
フィールドが有効なURLであることをバリデートします。The field under validation must be a valid URL.
有効と見なす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',
ulidulid
フィールドが有効なULID(Universally Unique Lexicographically Sortable Identifier)であることをバリデートします。The field under validation must be a valid Universally Unique Lexicographically Sortable Identifier[https://github.com/ulid/spec] (ULID).
uuiduuid
フィールドが有効な、RFC 4122(バージョン1、3、4、5)universally unique identifier (UUID)であることをバリデートします。The field under validation must be a valid RFC 4122 (version 1, 3, 4, or 5) universally unique identifier (UUID).
条件付きでルールを追加するConditionally Adding Rules
フィールドが特定値を持つ場合にバリデーションを飛ばすSkipping Validation When Fields Have Certain Values
他のフィールドに指定値が入力されている場合は、バリデーションを飛ばしたい状況がときどき起きるでしょう。exclude_if
バリデーションルールを使ってください。appointment_date
とdoctor_name
フィールドは、has_appointment
フィールドがfalse
値の場合バリデートされません。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',
]);
もしくは逆にexclude_unless
ルールを使い、他のフィールドに指定値が入力されていない場合は、バリデーションを行わないことも可能です。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
状況によっては、フィールドがバリデーション対象のデータに存在する場合にのみ、フィールドに対してバリデーションチェックを実行したい場合があります。これをすばやく実行するには、sometimes
ルールをルールリストに追加します。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:
$v = Validator::make($data, [
'email' => 'sometimes|required|email',
]);
上の例ではemail
フィールドが、$data
配列の中に存在している場合のみバリデーションが実行されます。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].
複雑な条件のバリデーションComplex Conditional Validation
ときどきもっと複雑な条件のロジックによりバリデーションルールを追加したい場合も起きます。たとえば他のフィールドが100より大きい場合のみ、指定したフィールドが入力されているかをバリデートしたいときなどです。もしくは2つのフィールドのどちらか一方が存在する場合は、両方共に値を指定する必要がある場合です。こうしたルールを付け加えるのも面倒ではありません。最初にValidator
インスタンスを生成するのは、固定ルールの場合と同じです。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|numeric',
]);
私たちのWebアプリケーションがゲームコレクター向けであると仮定しましょう。ゲームコレクターがアプリケーションに登録し、100を超えるゲームを所有している場合は、なぜこれほど多くのゲームを所有しているのかを説明してもらいます。たとえば、ゲームの再販店を経営している場合や、ゲームの収集を楽しんでいる場合などです。この要件を条件付きで追加するには、Validator
インスタンスのsometimes
メソッドが使用できます。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;
});
sometimes
メソッドに渡す最初の引数は、条件付きでバリデーションするフィールドの名前です。2番目の引数は、追加するルールのリストです。3番目の引数として渡すクロージャがtrue
を返す場合、ルールが追加されます。この方法で、複雑な条件付きバリデーションを簡単に作成できます。複数のフィールドに条件付きバリデーションを一度に追加することもできます。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: クロージャへ渡される
$input
パラメーターは、Illuminate\Support\Fluent
のインスタンスであり、バリデーション下の入力とファイルへアクセスするために使用できます。[!NOTE]
The$input
parameter passed to your closure will be an instance ofIlluminate\Support\Fluent
and may be used to access your input and files under validation.
複雑な条件の配列バリデーションComplex Conditional Array Validation
インデックスがわからない、入れ子になった同じ配列の中にある別のフィールドに基づいて、あるフィールドを検証したいことがあります。このような場合には、クロージャへ第2引数を渡してください。第2引数には、配列中のバリデーション対象の現アイテムが渡されます。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';
});
クロージャへ渡される$input
パラメータと同様に、$item
パラメータは属性データが配列の場合はIlluminate\Support\Fluent
のインスタンス、そうでない場合は文字列になります。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
array
バリデーションルールのドキュメントで説明したように、array
ルールは、許可する配列キーのリストを受け入れます。配列内にその他のキーが存在する場合、バリデーションは失敗します。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;
$input = [
'user' => [
'name' => 'Taylor Otwell',
'username' => 'taylorotwell',
'admin' => true,
],
];
Validator::make($input, [
'user' => 'array:name,username',
]);
一般的に、配列内に存在することが許される配列キーを常に指定する必要があります。そうしないと、バリデータのvalidate
とvalidated
メソッドは他のネストした配列バリデーションルールにより検証されていなくても、配列とそのすべてのキーを含むバリデーション済みデータをすべて返してしまうことになります。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
ネストした配列ベースフォームの入力フィールドをバリデーションするのが、面倒である必要はありません。配列内の属性をバリデーションするには、「ドット記法」が使えます。たとえば、HTTPリクエストにphotos[profile]
フィールドが含まれている場合、次のように検証します。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(), [
'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',
]
],
ネストした配列データへのアクセスAccessing Nested Array Data
バリデーションルールを属性に割り当てる際に、ネストした配列要素の値にアクセスする必要が起きることがあります。このような場合は、Rule::forEach
メソッドを使用します。forEach
メソッドは、バリデーション対象の配列属性の繰り返しごとに呼び出すクロージャを引数に取り、値と明示的で完全に展開された属性名を受け取ります。クロージャは、配列の要素に割り当てるルールの配列を返す必要があります。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
配列のバリデーションを行うとき、失敗した特定項目のインデックスや位置をアプリケーションのエラーメッセージから参照したいことがあります。これを行うには、[カスタムバリデーションメッセージ]
(#manual-customizing-the-error-messages)へ、:index
(0始点)と:position
(1始点)のプレースホルダを使ってください。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' => '',
],
],
];
Validator::validate($input, [
'photos.*.description' => 'required',
], [
'photos.*.description.required' => 'Please describe photo #:position.',
]);
上記の例で、バリデーションは失敗し、*"Please describe photo #2"*がユーザーに表示されます。Given the example above, validation will fail and the user will be presented with the following error of "Please describe photo #2."
必要であれば、second-index
、second-position
、third-index
、third-position
などを使って、さらに深くネストしたインデックスやポジションを参照できます。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では、アップロードされたファイルを検証するため、mimes
、image
、min
、max
など様々なバリデーションルールを提供しています。ファイルのバリデーションを行う際に、これらのルールを個別に指定することも可能ですが、便利なようにファイルバリデーションルールビルダも提供しています。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),
],
]);
アプリケーションがユーザーからアップロードされた画像を受け取る場合、File
ルールのimage
コンストラクタメソッドを使用して、アップロードされるファイルが画像であることを指定することができます。さらに、dimensions
ルールを使用して、画像の大きさを制限することもできます。If
your
application
accepts
images
uploaded
by
your
users,
you
may
use
the
File
rule's
image
constructor
method
to
indicate
that
the
uploaded
file
should
be
an
image.
In
addition,
the
dimensions
rule
may
be
used
to
limit
the
dimensions
of
the
image:
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)),
],
]);
dimensionsルールのドキュメントに記載しています。[!NOTE]
Note: 画像サイズのバリデーションに関するより詳しい情報は、
More information regarding validating image dimensions may be found in the dimension rule documentation[#rule-dimensions].
ファイルサイズFile Sizes
使いやすいように、最小ファイルサイズと最大ファイルサイズは、ファイルサイズの単位を示すサフィックス付きの文字列として指定できます。kb
、mb
、gb
、tb
のサフィックスをサポートしています。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::image()
->min('1kb')
->max('10mb')
ファイルタイプFile Types
types
メソッドを呼び出すときには拡張子を指定するだけですが、このメソッドは実際にファイルの内容を読み込んで、MIMEタイプを推測し、バリデーションします。MIME
タイプとそれに対応する拡張子の完全なリストは、次の場所にあります。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:
https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
パスワードのバリデーションValidating Passwords
パスワードが十分なレベルの複雑さがあることを確認するために、LaravelのPassword
ルールオブジェクトを使用します。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)],
]);
Password
ルールオブジェクトを使用すると、文字・数字・記号を最低1文字必須にしたり、文字種を組み合わせたりのように、パスワードの指定をアプリケーションで使用する複雑さの要件に合うよう簡単にカスタマイズできます。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:
// 最低8文字必要
Password::min(8)
// 最低1文字の文字が必要
Password::min(8)->letters()
// 最低大文字小文字が1文字ずつ必要
Password::min(8)->mixedCase()
// 最低一文字の数字が必要
Password::min(8)->numbers()
// 最低一文字の記号が必要
Password::min(8)->symbols()
さらに、uncompromised
メソッドを使って、公開されているパスワードのデータ漏洩によるパスワード漏洩がないことを確認することもできます。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()
内部的には、Password
ルールオブジェクトは、k-Anonymityモデルを使用して、ユーザーのプライバシーやセキュリティを犠牲にすることなく、パスワードがhaveibeenpwned.comサービスを介してリークされているかを判断しています。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.
デフォルトでは、データリークに少なくとも1回パスワードが表示されている場合は、侵害されたと見なします。uncompromised
メソッドの最初の引数を使用してこのしきい値をカスタマイズできます。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:
// 同一のデータリークにおいて、パスワードの出現回数が3回以下であることを確認
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()
デフォルトパスワードルールの定義Defining Default Password Rules
パスワードのデフォルトバリデーションルールをアプリケーションの一箇所で指定できると便利でしょう。クロージャを引数に取るPassword::defaults
メソッドを使用すると、これを簡単に実現できます。defaults
メソッドへ渡すクロージャは、パスワードルールのデフォルト設定を返す必要があります。通常、defaults
ルールはアプリケーションのサービスプロバイダの1つのboot
メソッド内で呼び出すべきです。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;
/**
* アプリケーションの全サービスの初期処理
*/
public function boot(): void
{
Password::defaults(function () {
$rule = Password::min(8);
return $this->app->isProduction()
? $rule->mixedCase()->uncompromised()
: $rule;
});
}
そして、バリデーションで特定のパスワードへデフォルトルールを適用したい場合に、引数なしでdefaults
メソッドを呼び出します。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()],
時には、デフォルトのパスワードバリデーションルールへ追加ルールを加えたい場合があります。このような場合には、rules
メソッドを使用します。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は有用な数多くのバリデーションルールを提供しています。ただし、独自のものを指定することもできます。カスタムバリデーションルールを登録する1つの方法は、ルールオブジェクトを使用することです。新しいルールオブジェクトを生成するには、make:rule
Artisanコマンドを使用できます。このコマンドを使用して、文字列が大文字であることを確認するルールを生成してみましょう。Laravelは新しいルールをapp/Rules
ディレクトリに配置します。このディレクトリが存在しない場合、Artisanコマンドを実行してルールを作成すると、Laravelがそのディレクトリを作成します。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
ルールを作成したら、次はその動作を定義します。ルールオブジェクトには、validate
というメソッドが1つあります。このメソッドは、属性名とその値、バリデーションに失敗したときに、エラーメッセージとともに呼び出されるコールバックを受け取ります。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
{
/**
* バリデーションルールの実行
*/
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
$fail
クロージャへ文字列のエラーメッセージを指定する代わりに、翻訳文字列キーを指定し、Laravelへエラーメッセージの翻訳を指示できます。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();
}
必要に応じ、プレースホルダを置き換えたり、translate
メソッドの第1引数と第2引数として使用する言語を指定することもできます。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
カスタムバリデーションルールクラスがバリデーション下の他のすべてのデータへアクセスする必要がある場合、そのルールクラスにIlluminate\Contracts\Validation\DataAwareRule
インターフェイスを実装してください。このインターフェイスは、クラスへsetData
メソッドの定義を要求します。このメソッドはLaravelにより自動的に(バリデーション処理前に)、バリデーション対象の全データで呼び出されます。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
{
/**
* バリデーション下の全データ
*
* @var array<string, mixed>
*/
protected $data = [];
// ...
/**
* バリデーション下のデータをセット
*
* @param array<string, mixed> $data
*/
public function setData(array $data): static
{
$this->data = $data;
return $this;
}
}
または、バリデーションルールが、バリデーションを行うバリデータインスタンスへのアクセスを必要とする場合は、ValidatorAwareRule
インターフェイスを実装してください。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
{
/**
* バリデータインスタンス
*
* @var \Illuminate\Validation\Validator
*/
protected $validator;
// ...
/**
* 現用バリデータのセット
*/
public function setValidator(Validator $validator): static
{
$this->validator = $validator;
return $this;
}
}
クロージャの使用Using Closures
アプリケーション全体でカスタムルールの機能が1回だけ必要な場合は、ルールオブジェクトの代わりにクロージャを使用できます。クロージャは、属性の名前、属性の値、およびバリデーションが失敗した場合に呼び出す必要がある$fail
コールバックを受け取ります。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
デフォルトでは、バリデーションされる属性が存在しないか、空の文字列が含まれている場合、カスタムルールを含む通常のバリデーションルールは実行されません。たとえば、unique
ルールは空の文字列に対して実行されません。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;
$rules = ['name' => 'unique:users,name'];
$input = ['name' => ''];
Validator::make($input, $rules)->passes(); // true
属性が空の場合でもカスタムルールを実行するには、ルールがその属性を必要とすることを示す必要があります。簡単に新しい暗黙のルールオブジェクトを生成するには、make:rule
Artisanコマンドに、--implicit
オプションを付けて使用します。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]
Warning! 「暗黙の」ルールは、属性が必要であることを暗黙的にします。欠落している属性または空の属性を実際に無効にするかどうかは、あなた次第です。
An "implicit" rule only implies that the attribute is required. Whether it actually invalidates a missing or empty attribute is up to you.