Readouble

Laravel 5.7 バリデーション

イントロダクションIntroduction

Laravelは入力されたデータに対するバリデーションの様々なアプローチを提供しています。Laravelの基本コントローラクラスはパワフルでバラエティー豊かなバリデーションルールを使いHTTPリクエストをバリデーションするために便利な手法を提供している、ValidatesRequestsトレイトをデフォルトで使用しています。Laravel provides several different approaches to validate your application's incoming data. By default, Laravel's base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP request with a variety of powerful validation rules.

クイックスタートValidation Quickstart

パワフルなバリデーション機能を学ぶために、フォームバリデーションとユーザーにエラーメッセージを表示する完全な例を見てください。To learn about Laravel's powerful validation features, let's look at a complete example of validating a form and displaying the error messages back to the user.

ルート定義Defining The Routes

まず、routes/web.phpファイルに以下のルートを定義してあるとしましょう。First, let's assume we have the following routes defined in our routes/web.php file:

Route::get('post/create', 'PostController@create');

Route::post('post', 'PostController@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 these routes. We'll leave the store method empty for now:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PostController extends Controller
{
    /**
     * 新ブログポスト作成フォームの表示
     *
     * @return Response
     */
    public function create()
    {
        return view('post.create');
    }

    /**
     * 新しいブログポストの保存
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        // ブログポストのバリデーションと保存コード…
    }
}

バリデーションロジックWriting The Validation Logic

これで新しいブログポストに対するバリデーションロジックをstoreメソッドに埋め込む準備ができました。そのためには、Illuminate\Http\Requestオブジェクトが提供する、validateメソッドを使います。バリデーションルールに成功すると、コードは通常通り続けて実行されます。逆にバリデーションに失敗すると、例外が投げられ、ユーザーに対し自動的に適切なエラーレスポンスが返されます。伝統的なHTTPリクエストの場合は、リダイレクトレスポンスが生成され、一方でAJAXリクエストにはJSONレスポンスが返されます。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 exception will be thrown and the proper error response will automatically be sent back to the user. In the case of a traditional HTTP request, a redirect response will be generated, while a JSON response will be sent for AJAX requests.

validateメソッドをもっとよく理解するため、storeメソッドに取り掛かりましょう。To get a better understanding of the validate method, let's jump back into the store method:

/**
 * 新ブログポストの保存
 *
 * @param  Request  $request
 * @return Response
 */
public function store(Request $request)
{
    $validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    // ブログポストは有効
}

ご覧のとおりに、実行したいバリデーションルールをvalidateメソッドへ渡します。繰り返しますが、バリデーションに失敗すれば、適切なレスポンスが自動的に生成されます。バリデーションに成功すれば、コントローラは続けて通常通り実行されます。As you can see, we pass the desired validation rules into the validate method. Again, if the validation fails, the proper response will automatically be generated. If the validation passes, our controller will continue executing normally.

最初のバリデーション失敗時に停止Stopping On First Validation Failure

最初のバリデーションに失敗したら、残りのバリデーションルールの判定を停止したいことも、時々あります。このためには、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 your HTTP request contains "nested" parameters, you may specify them in your validation rules using "dot" syntax:

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

バリデーションエラー表示Displaying The Validation Errors

ではやって来たリクエストの入力が指定したバリデーションルールに当てはまらなかった場合はどうなるんでしょう? 既に説明した通り、Laravelは自動的にユーザーを以前のページヘリダイレクトします。付け加えて、バリデーションエラーは全部自動的にフラッシュデータとしてセッションへ保存されます。So, what if the incoming request parameters do not pass the given validation rules? As mentioned previously, Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors will automatically be flashed to the session[/docs/{{version}}/session#flash-data].

GETルートのビューへエラーメッセージを明示的に結合する必要がないことに注目してください。これはつまり、Laravelはいつもセッションデータの中にエラーの存在をチェックしており、見つけた場合は自動的に結合しているからです。$errors変数はIlluminate\Support\MessageBagのインスタンスです。このオブジェクトの詳細は、ドキュメントを参照してください。Again, notice that we did not have to explicitly bind the error messages to the view in our GET route. This is because Laravel will check for errors in the session data, and automatically bind them to the view if they are available. The $errors variable will be an instance of Illuminate\Support\MessageBag. For more information on working with this object, check out its documentation[#working-with-error-messages].

lightbulb">Tip!! $errors変数はwebミドルウェアグループに所属する、Illuminate\View\Middleware\ShareErrorsFromSessionミドルウェアによりビューに結合されます。このミドルウェアが適用される場合は、いつでもビューの中で$errors変数が使えます。$errors変数はいつでも定義済みであると想定でき、安心して使えます。{tip} The $errors variable is bound to the view by the Illuminate\View\Middleware\ShareErrorsFromSession middleware, which is provided by the web middleware group. When this middleware is applied an $errors variable will always be available in your views, allowing you to conveniently assume the $errors variable is always defined and can be safely used.

この例では、バリデーションに失敗すると、エラーメッセージをビューで表示できるように、コントローラの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>ポスト作成</h1>

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

<!-- ポスト作成フォーム -->

オプションフィールドに対する注意A Note On Optional Fields

LaravelはTrimStringsConvertEmptyStringsToNullミドルウェアをアプリケーションのデフォルトグローバルミドルウェアスタックに含んでいます。これらのミドルウェアはApp\Http\Kernelクラスでリストされています。このため、バリデータがnull値が無効であると判定されないように、オプションフィールドへnullableを付ける必要がたびたび起きるでしょう。By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware are listed in the stack by the App\Http\Kernel class. 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.

AJAXリクエストとバリデーションAJAX Requests & Validation

この例ではアプリケーションにデータを送るために伝統的なフォームを使いました。しかし、多くのアプリケーションでAJAXリクエストが使用されています。AJAXリクエストにvalidateメソッドを使う場合、Laravelはリダイレクトレスポンスを生成しません。代わりにバリデーションエラーを全部含んだJSONレスポンスを生成します。このJSONレスポンスは422 HTTPステータスコードで送られます。In this example, we used a traditional form to send data to the application. However, many applications use AJAX requests. When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

フォームリクエストバリデーションForm Request Validation

フォームリクエスト作成Creating Form Requests

より複雑なバリデーションのシナリオでは、「フォームリクエスト」を生成したほうが良いでしょう。フォームリクエストは、バリデーションロジックを含んだカスタムリクエストクラスです。フォームリクエストクラスを作成するには、make:request Artisan CLIコマンドを使用します。For more complex validation scenarios, you may wish to create a "form request". Form requests are custom request classes that contain validation logic. To create a form request class, use the make:request Artisan CLI command:

php artisan make:request StoreBlogPost

生成されたクラスは、app/Http/Requestディレクトリへ設置されます。このディレクトリが存在しなくても、make:requestコマンドを実行すれば作成されます。では、バリデーションルールを少しrulesメソッドへ追加してみましょう。The generated class will be placed in the app/Http/Requests directory. If this directory does not exist, it will be created when you run the make:request command. Let's add a few validation rules to the rules method:

/**
 * リクエストに適用するバリデーションルールを取得
 *
 * @return array
 */
public function rules()
{
    return [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ];
}

lightbulb">Tip!! rulesメソッドの引数として、必要な依存をタイプヒントで指定できます。それらはLaravelのサービスコンテナにより、自動的に依存解決されます。{tip} You may type-hint any dependencies you need within the rules 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:

/**
 * ブログポストの保存
 *
 * @param  StoreBlogPost  $request
 * @return Response
 */
public function store(StoreBlogPost $request)
{
    // 送信されたリクエストは正しい

    // バリデーション済みデータの取得
    $validated = $request->validated();
}

バリデーションに失敗すると、前のアドレスにユーザーを戻すために、リダイレクトレスポンスが生成されます。エラーも表示できるように、フラッシュデーターとしてセッションに保存されます。もしリクエストがAJAXリクエストであれば、バリデーションエラーを表現するJSONを含んだ、422ステータスコードの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 AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.

フォームリクエストへのAfterフックを追加Adding After Hooks To Form Requests

フォームリクエストへ"after"フックを追加したい場合は、withValidatorメソッドを使用します。このメソッドは完全に構築されたバリデータを受け取るため、バリデーションルールが実際に評価される前に、バリデータのどんなメソッドも呼び出すことができます。If you would like to add an "after" hook to a form request, you may use the withValidator method. This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are actually evaluated:

/**
 * バリデータインスタンスの設定
 *
 * @param  \Illuminate\Validation\Validator  $validator
 * @return void
 */
public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($this->somethingElseIsInvalid()) {
            $validator->errors()->add('field', 'Something is wrong with this field!');
        }
    });
}

フォームリクエストの認可Authorizing Form Requests

フォームリクエストクラスはauthorizeメソッドも用意しています。このメソッドでは認証されているユーザーが、指定されたリソースを更新する権限を実際に持っているのかを確認します。たとえば、ユーザーが更新しようとしているブログコメントを実際に所有しているかを判断するとしましょう。The form request class also contains an authorize method. Within this method, you may check if the authenticated user actually has the authority to update a given resource. For example, you may determine if a user actually owns a blog comment they are attempting to update:

/**
 * ユーザーがこのリクエストの権限を持っているかを判断する
 *
 * @return bool
 */
public function authorize()
{
    $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}');

authorizeメソッドがfalseを返すと、403ステータスコードのHTTPレスポンスが自動的に返され、コントローラメソッドは実行されません。If the authorize method returns false, a HTTP response with a 403 status code will automatically be returned and your controller method will not execute.

アプリケーションの他の場所で認証のロジックを行おうと設計しているのでしたら、authorizeメソッドからtrueを返してください。If you plan to have authorization logic in another part of your application, return true from the authorize method:

/**
 * ユーザーがこのリクエストの権限を持っているかを判断する
 *
 * @return bool
 */
public function authorize()
{
    return true;
}

lightbulb">Tip!! authorizeメソッドの引数として、必要な依存をタイプヒントで指定できます。それらはLaravelのサービスコンテナにより、自動的に依存解決されます。{tip} You may type-hint any dependencies you need within the authorize 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
 */
public function messages()
{
    return [
        'title.required' => 'A title is required',
        'body.required'  => 'A message is required',
    ];
}

バリデーション属性のカスタマイズCustomizing The Validation Attributes

バリデーションメッセージの:attribute部分をカスタム属性名へ置き換えたい場合は、attributesメソッドをオーバーライドし、カスタム名を指定してください。If you would like the :attribute portion 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
 */
public function attributes()
{
    return [
        'email' => 'email address',
    ];
}

バリデータの生成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 Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PostController extends Controller
{
    /**
     * 新しいブログポストの保存
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

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

        // ブログポストの保存処理…
    }
}

makeメソッドの第1引数は、バリデーションを行うデータです。第2引数はそのデータに適用するバリデーションルールです。The first argument passed to the make method is the data under validation. The second argument is the validation rules that should be applied to the data.

リクエストのバリデーションが失敗するかを確認した後、セッションにエラーメッセージをフラッシュデータとして保存するためにwithErrorsメソッドが利用できます。このメソッドを使うと、簡単にユーザーに情報を表示できるようにするため、リダイレクトの後でビューに対し$errors変数を自動的に共有します。withErrorsメソッドはバリデータかMessageBag、PHPの配列を受け取ります。After checking if the request validation failed, you may use the withErrors method to flash the error messages to the session. When using this method, the $errors variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user. The withErrors method accepts a validator, a MessageBag, or a PHP array.

自動リダイレクトAutomatic Redirection

バリデータインスタンスを自分で生成したいが、リクエストのvalidateメソッドが提供する自動リダイレクト機能を使用したい場合は、生成したバリデータインスタンスのvalidateメソッドを呼び出すこともできます。バリデーションに失敗すると、ユーザーは自動的にリダイレクトされるか、AJAXリクエストの場合は、JSONリクエストが返されます。If you would like to create a validator instance manually but still take advantage of the automatic redirection offered by the requests'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 AJAX request, a JSON response will be returned:

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

名前付きエラーバッグNamed Error Bags

1ページの中に複数のフォームを入れている場合は、特定のフォームのエラーメッセージを受け取れるように、MessageBagへ名前を付けてください。withErrorsの第2引数に名前を渡します。If you have multiple forms on a single page, you may wish to name the MessageBag of errors, allowing you to retrieve the error messages for a specific form. 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') }}

バリデーション後のフックAfter Validation Hook

バリデータにはさらに、バリデーションが終了した時点で実行するコールバックを付け加えられます。これにより、追加のバリデーションを行い、さらにエラーメッセージコレクションにエラーメッセージを追加することが簡単にできます。バリデータインスタンスのafterメソッドを使ってみましょう。The validator also allows you to attach callbacks to be run after validation is completed. This allows you to easily perform further validation and even add more error messages to the message collection. To get started, use the after method on a validator instance:

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

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

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

エラーメッセージの操作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 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')) {
    //
}

カスタムエラーメッセージCustom Error Messages

必要であればバリデーションでデフォルトのメッセージの代わりに、カスタムエラーメッセージを使うことができます。カスタムメッセージを指定するにはいくつか方法があります。最初の方法はValidator::makeメソッドの第3引数として、カスタムメッセージを渡す方法です。If needed, you may use custom error messages for validation instead of the defaults. There are several ways to specify custom messages. First, you may pass the custom messages as the third argument to the Validator::make method:

$messages = [
    'required' => 'The :attribute field is required.',
];

$validator = Validator::make($input, $rules, $messages);

この例中の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 field. 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 e-mail address!',
];

言語ファイルでカスタムメッセージ指定Specifying Custom Messages In Language Files

多くの場合、Validatorに直接カスタムメッセージを渡すよりは言語ファイルに指定したいですよね。ならばresources/lang/xx/validation.php言語ファイルのcustom配列にメッセージを追加してください。In most cases, you will probably specify your custom messages in a language file instead of passing them directly to the Validator. To do so, add your messages to custom array in the resources/lang/xx/validation.php language file.

'custom' => [
    'email' => [
        'required' => 'We need to know your e-mail address!',
    ],
],

言語ファイル中のカスタム属性名の指定Specifying Custom Attributes In Language Files

バリデーションメッセージの:attribute部分をカスタムアトリビュート名で置き換えたい場合は、resources/lang/xx/validation.php言語ファイルのattributes配列でカスタム名を指定してください。If you would like the :attribute portion of your validation message to be replaced with a custom attribute name, you may specify the custom name in the attributes array of your resources/lang/xx/validation.php language file:

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

言語ファイルでカスタム値を指定Specifying Custom Values In Language Files

バリデーションメッセージの:value部分をその値のカスタム表現へ置き換える必要がある場合も起きます。たとえば、payment_typeccという値であれば、クレジットカード番号ルールを指定する必要があると想像してください。Sometimes you may 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:

$request->validate([
    '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の代わりに、validation言語ファイルの中でvalues配列を定義することにより、カスタム表現値を指定します。Instead of displaying cc as the payment type value, you may specify a custom value representation in your validation language file by defining a values array:

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

これで、バリデーションルールに失敗した場合、以下のようなメッセージが表示されます。Now if the validation rule fails it will produce the following 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:

acceptedaccepted

そのフィールドがyeson1trueであることをバリデートします。これは「サービス利用規約」同意のバリデーションに便利です。The field under validation must be yes, on, 1, or true. This is useful for validating "Terms of Service" acceptance.

active_urlactive_url

フィールドが、dns_get_record PHP関数により、有効なAかAAAAレコードであることをバリデートします。The field under validation must have a valid A or AAAA record according to the dns_get_record PHP function.

after:日付after:date

フィールドの値が与えられた日付より後であるかバリデーションします。日付はPHPのstrtotime関数で処理されます。The field under validation must be a value after a given date. The dates will be passed into the strtotime PHP function:

'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

フィールドが全部アルファベット文字であることをバリデートします。The field under validation must be entirely alphabetic characters.

alpha_dashalpha_dash

フィールドが全部アルファベット文字と数字、ダッシュ(-)、下線(_)であることをバリデートします。The field under validation may have alpha-numeric characters, as well as dashes and underscores.

alpha_numalpha_num

フィールドが全部アルファベット文字と数字であることをバリデートします。The field under validation must be entirely alpha-numeric characters.

arrayarray

フィールドが配列タイプであることをバリデートします。The field under validation must be a PHP array.

bailbail

バリデーションに初めて失敗した時点で、残りのルールのバリデーションを中止します。Stop running validation rules after the first validation failure.

before:日付before:date

フィールドが指定された日付より前であることをバリデートします。日付はPHPのstrtotime関数で処理されます。さらに、afterルールと同様に、日付け値の代わりにバリデーション対象のフィールド名を指定することができます。The field under validation must be a value preceding the given date. The dates will be passed into the PHP strtotime function. 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

フィールドが指定した日付以前であることをバリデートします。日付はPHPのstrtotime関数で処理されます。さらに、afterルールと同様に、日付け値の代わりにバリデーション対象のフィールド名を指定することができます。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 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. Strings, numerics, arrays, and files are evaluated in the same fashion as the size[#rule-size] rule.

booleanboolean

フィールドが論理値として有効であることをバリデートします。受け入れられる入力は、truefalse10"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

フィールドがそのフィールド名+_confirmationフィールドと同じ値であることをバリデートします。例えば、バリデーションするフィールドがpasswordであれば、同じ値のpassword_confirmationフィールドが入力に存在していなければなりません。The field under validation must have a matching field of foo_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input.

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

バリデーションされる値が、指定した日付と同じことをバリデートします。日付は、PHPのstrtotime関数へ渡されます。The field under validation must be equal to the given date. The dates will be passed into the PHP strtotime function.

date_format:フォーマットdate_format:format

バリデーションされる値がフォーマット定義と一致するか確認します。バリデーション時にはdatedate_formatどちらかを使用しなくてはならず、両方はできません。The field under validation must match the given format. You should use either date or date_format when validating a field, not both.

different:フィールドdifferent:field

フィールドが指定されたフィールドと異なった値を指定されていることをバリデートします。The field under validation must have a different value than field.

digits:digits:value

フィールドが数値で、の桁数であることをバリデートします。The field under validation must be numeric and must have an exact length of value.

digits_between:最小値,最大値digits_between:min,max

フィールドが整数で、桁数が最小値から最大値の間であることをバリデートします。The field under 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_widthmax_widthmin_heightmax_heightwidthheight、_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 statement 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\Validation\Rule;

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

distinctdistinct

対象が配列の時、フィールドに重複した値がないことをバリデートします。When working with arrays, the field under validation must not have any duplicate values.

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

emailemail

フィールドがメールアドレスとして正しいことをバリデートします。The field under validation must be formatted as an e-mail address.

exists:テーブル,カラムexists:table,column

フィールドの値が、指定されたデータベーステーブルに存在することをバリデートします。The field under validation must exist on a given database table.

基本的なExistsルールの使用法Basic Usage Of Exists Rule

'state' => 'exists:states'

columnオプションを指定しない場合、フィールド名が利用されます。If the column option is not specified, the field name will be used.

カスタムカラム名の指定Specifying A Custom Column 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 using "dot" syntax:

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

バリデーションルールで実行されるクエリをカスタマイズしたい場合は、ルールをスラスラと定義できる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\Validation\Rule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::exists('staff')->where(function ($query) {
            $query->where('account_id', 1);
        }),
    ],
]);

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. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size rule.

gte:fieldgte:field

フィールドが指定したフィールド以上であることをバリデートします。2つのフィールドは同じタイプでなくてはなりません。文字列、数値、配列、ファイルは、sizeルールと同じ規約により評価します。The field under validation must be greater than or equal to the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size rule.

imageimage

フィールドで指定されたファイルが画像(jpg、png、bmp、gif、svg)であることをバリデートします。The file under validation must be an image (jpeg, png, bmp, gif, or svg)

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\Validation\Rule;

Validator::make($data, [
    'zones' => [
        'required',
        Rule::in(['first-zone', 'second-zone']),
    ],
]);

in_array:他のフィールド.*in_array:anotherfield.*

フィールドが、他のフィールドの値のどれかであることをバリデートします。The field under validation must exist in anotherfield's values.

integerinteger

フィールドが整数値であることをバリデートします。The field under validation must be an integer.

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.

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.

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.

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

MIMEルールの基本的な使用法Basic Usage Of MIME Rule

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

拡張子だけを限定する必要があるとしても、このルールはファイルのMIMEタイプに基づき、ファイルの内容を読み、MIMEタイプを推測することでバリデーションを行います。Even though you only need to specify the extensions, this rule actually validates against the MIME type of the file by reading the file's contents and guessing its MIME type.

MIMEタイプと対応する拡張子の完全なリストは、https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.typesで確認できます。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[https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types]

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.

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.

このルールは内部でPHPのpreg_match関数を使用しています。指定された正規表現はデリミッタも含め、preg_matchで要求されているのと同じ形式に従う必要があります。たとえば、'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'.

注目: regexnot_regexパターンを使用する場合はルールをパイプ(縦棒)で区切らず、ルールの配列で指定する必要があります。特に正規表現に縦棒を含んでいる場合に該当します。Note: When using the regex / not_regex patterns, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

nullablenullable

フィールドがnullでも良いことをバリデートします。これは特にnull値を含む文字列や整数のようなプリミティブをバリデートする場合に便利です。The field under validation may be null. This is particularly useful when validating primitive such as strings and integers that can contain null values.

numericnumeric

フィールドは数値であることをバリデートします。The field under validation must be numeric.

presentpresent

フィールドが存在していることをバリデートしますが、存在していれば空を許します。The field under validation must be present in the input data but can be empty.

regex:正規表現regex:pattern

フィールドが指定された正規表現にマッチすることをバリデートします。The field under validation must match the given regular expression.

このルールは内部でPHPのpreg_match関数を使用しています。指定された正規表現はデリミッタも含め、preg_matchで要求されているのと同じ形式に従う必要があります。たとえば、'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'.

注目: regexnot_regexパターンを使用する場合はルールをパイプ(縦棒)で区切らず、ルールの配列で指定する必要があります。特に正規表現に縦棒を含んでいる場合に該当します。Note: When using the regex / not_regex patterns, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

requiredrequired

フィールドが入力データに存在しており、かつ空でないことをバリデートします。フィールドは以下の条件の場合、「空」であると判断されます。The field under validation must be present in the input data and not empty. A field is considered "empty" if one of the following conditions are true:

  • 値がnullである。The value is null.
  • 値が空文字列である。The value is an empty string.
  • 値が空の配列か、空のCountableオブジェクトである。The value is an empty array or empty Countable 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メソッドを使用してください。このメソッドは論理値かクロージャを引数に取ります。クロージャが渡された場合、そのクロージャはバリデーション対象が要求されているかを示すため、turefalseを返す必要があります。If you would like to construct a more complex condition for the required_if rule, you may use the Rule::requiredIf method. This methods 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\Validation\Rule;

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

Validator::make($request->all(), [
    'role_id' => Rule::requiredIf(function () use ($request) {
        return $request->user()->is_admin;
    }),
]);

required_unless:他のフィールド,,...required_unless:anotherfield,value,...

他のフィールドのどれとも一致していない場合、このフィールドが存在し、かつ空でないことをバリデートします。The field under validation must be present and not empty unless the anotherfield field is equal to any value.

required_with:foo,bar,...required_with:foo,bar,...

指定した他のフィールドが一つでも存在している場合、このフィールドが存在し、かつ空でないことをバリデートします。The field under validation must be present and not empty only if any of the other specified fields are present.

required_with_all:foo,bar,...required_with_all:foo,bar,...

指定した他のフィールドがすべて存在している場合、このフィールドが存在し、かつ空でないことをバリデートします。The field under validation must be present and not empty only if all of the other specified fields are present.

required_without:foo,bar,...required_without:foo,bar,...

指定した他のフィールドのどれか一つでも存在していない場合、このフィールドが存在し、かつ空でないことをバリデートします。The field under validation must be present and not empty only when any of the other specified fields are not present.

required_without_all:foo,bar,...required_without_all:foo,bar,...

指定した他のフィールドがすべて存在していない場合、このフィールドが存在し、かつ空でないことをバリデートします。The field under validation must be present and not empty only when all of the other specified fields are not present.

same:フィールドsame:field

フィールドが、指定されたフィールドと同じ値であることをバリデートします。The given field must match the field under validation.

size:size:value

フィールドは指定されたと同じサイズであることをバリデートします。文字列の場合、は文字長です。数値項目の場合、は整数値です。配列の場合、は配列の個数(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. For an array, size corresponds to the count of the array. For files, size corresponds to the file size in kilobytes.

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

timezone_identifiers_list PHP関数の値に基づき、フィールドがタイムゾーンとして識別されることをバリデートします。The field under validation must be a valid timezone identifier according to the timezone_identifiers_list PHP function.

unique:テーブル,カラム,除外ID,IDカラムunique:table,column,except,idColumn

フィールドは指定されたデータベーステーブルで一意であることをバリデートします。columnオプションが指定されない場合、フィールド名が使用されます。The field under validation must be unique in a given database table. If the column option is not specified, the field name will be used.

カスタムカラム名の指定Specifying A Custom Column Name:

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

カスタムデータベース接続Custom Database Connection

場合により、バリデータにより生成されるデータベースクエリに、カスタム接続を設定する必要があるかもしれません。上記のバリデーションルール、unique:usersではクエリに対し、デフォルトデータベース接続が使用されます。これをオーバーライドするにはドット記法で、接続に続けテーブル名を指定してください。Occasionally, you may need to set a custom connection for database queries made by the Validator. As seen above, setting unique:users as a validation rule will use the default database connection to query the database. To override this, specify the connection and the table name using "dot" syntax:

'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 the unique check. For example, consider an "update profile" screen that includes the user's name, e-mail address, and location. You will probably want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address.

バリデータにユーザー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\Validation\Rule;

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

もし、テーブルの主キーとして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_id1であることを確認する制約を追加してみましょう。You may also specify additional query constraints by customizing the query using the where method. For example, let's add a constraint that verifies the account_id is 1:

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

urlurl

フィールドが有効なURLであることをバリデートします。The field under validation must be a valid URL.

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

項目存在時のバリデーション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 input array. 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.

lightbulb">Tip!! フィールドが常に存在しているが、空であることをバリデートする場合は、この追加フィールドに対する注意事項を確認してください。{tip} 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:

$v = Validator::make($data, [
    '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. To conditionally add this requirement, we can use the sometimes method on the Validator instance.

$v->sometimes('reason', 'required|max:500', function ($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 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:

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

lightbulb">Tip!! クロージャに渡される$inputパラメーターはIlluminate\Support\Fluentのインスタンスで、フィールドと入力値にアクセスするためのオブジェクトです。{tip} The $input parameter passed to your Closure will be an instance of Illuminate\Support\Fluent and may be used to access your input and files.

配列のバリデーションValidating Arrays

フォーム入力フィールドの配列をバリデーションするのに苦労する必要はありません。配列中の属性をバリデーションするために「ドット記法」が使えます。たとえば、送信されたHTTPリクエストに、photos[profile]フィールドが含まれているかをバリデーションするには、次のように行います。Validating 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:

$validator = Validator::make($request->all(), [
    'photos.profile' => 'required|image',
]);

配列の各要素をバリデーションすることもできます。たとえば、配列中の各メールアドレスの入力フィールドが、一位であることを確認するには、以下のように行います。You may also validate each element of an array. For example, to validate that each e-mail 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 your validation messages in your language files, making it a breeze to use a single validation message for array based fields:

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

カスタムバリデーションルールCustom Validation Rules

ルールオブジェクトの使用Using Rule Objects

Laravelは様々な便利なバリデーションルールを提供しています。しかし、独自のバリデーションも利用したいでしょう。カスタムバリデーションルールを登録する一つ目の方法は、ルールオブジェクトを使うやり方です。新しいルールオブジェクトを生成するには、make:rule Artisanコマンドを使用します。このコマンドを使用し、文字列が大文字であることをバリデートするルールを生成してみましょう。Laravelの新しいルールは、app/Rulesディレクトリに設置されます。Laravel provides a variety of helpful validation rules; however, you may wish to specify some of your own. One method of registering custom validation rules is using 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:

php artisan make:rule Uppercase

ルールを生成したら、動作を定義する準備ができました。ルールオブジェクトは2つのメソッドを含みます。passesmessageです。passesメソッドは属性の値と名前を受け取り、その属性値が有効であればtrue、無効であればfalseを返します。messageメソッドは、バリデーション失敗時に使用する、バリデーションエラーメッセージを返します。Once the rule has been created, we are ready to define its behavior. A rule object contains two methods: passes and message. The passes method receives the attribute value and name, and should return true or false depending on whether the attribute value is valid or not. The message method should return the validation error message that should be used when validation fails:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Uppercase implements Rule
{
    /**
     * バリデーションの成功を判定
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return strtoupper($value) === $value;
    }

    /**
     * バリデーションエラーメッセージの取得
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be uppercase.';
    }
}

もちろん、翻訳ファイルのエラーメッセージを返したい場合は、messageメソッドからtransヘルパを呼び出せます。You may call the trans helper from your message method if you would like to return an error message from your translation files:

/**
 * バリデーションエラーメッセージの取得
 *
 * @return string
 */
public function message()
{
    return trans('validation.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],
]);

クロージャの使用Using Closures

アプリケーション全体で一回のみカスタムルールの機能が必要な場合は、ルールオブジェクトの代わりにクロージャが使えます。属性名、属性の値、バリデーション失敗時に返す必要のある$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:

$validator = Validator::make($request->all(), [
    'title' => [
        'required',
        'max:255',
        function ($attribute, $value, $fail) {
            if ($value === 'foo') {
                $fail($attribute.' is invalid.');
            }
        },
    ],
]);

拡張の使用Using Extensions

カスタムバリデーションルールを登録するもう一つの方法では、Validatorファサードextendメソッドを使用します。カスタムバリデーションルールを登録するために、 サービスプロバイダの中で、このメソッドを使ってみましょう。Another method of registering custom validation rules is using the extend method on the Validator facade[/docs/{{version}}/facades]. Let's use this method within a service provider[/docs/{{version}}/providers] to register a custom validation rule:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * アプリケーションサービスの初期処理
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('foo', function ($attribute, $value, $parameters, $validator) {
            return $value == 'foo';
        });
    }

    /**
     * サービスプロバイダ登録
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

カスタムバリデータのクロージャは4つの引数を取ります。$attributeはバリデーションをしているフィールド、$valueはその値、$parametersはルールに渡された引数、最後はValidatorインスタンスです。The custom validator Closure receives four arguments: the name of the $attribute being validated, the $value of the attribute, an array of $parameters passed to the rule, and the Validator instance.

クロージャの代わりにextendメソッドへクラスとメソッドを渡すこともできます。You may also pass a class and method to the extend method instead of a Closure:

Validator::extend('foo', 'FooValidator@validate');

エラーメッセージの定義Defining The Error Message

カスタムルールに対するエラーメッセージを定義する必要もあります。インラインでカスタムエラーの配列を使うか、バリデーション言語ファイルにエントリーを追加するどちらかで行えます。このメッセージは属性とエラーメッセージを指定するだけの一次配列で、「カスタマイズ」した配列を入れてはいけません。You will also need to define an error message for your custom rule. You can do so either using an inline custom message array or by adding an entry in the validation language file. This message should be placed in the first level of the array, not within the custom array, which is only for attribute-specific error messages:

"foo" => "Your input was invalid!",

"accepted" => "The :attribute must be accepted.",

// 残りのバリデーションエラーメッセージ…

カスタムバリデーションルールを作成する場合、エラーメッセージのカスタムプレースフォルダも定義したいことがあります。前記の方法でカスタムバリデータを作成し、それからValidatorファサードのreplacerメソッドを呼びだしてください。これはサービスプロバイダbootメソッドの中で行います。When creating a custom validation rule, you may sometimes need to define custom placeholder replacements for error messages. You may do so by creating a custom Validator as described above then making a call to the replacer method on the Validator facade. You may do this within the boot method of a service provider[/docs/{{version}}/providers]:

/**
 * 全アプリケーションサービスの初期処理
 *
 * @return void
 */
public function boot()
{
    Validator::extend(...);

    Validator::replacer('foo', function ($message, $attribute, $rule, $parameters) {
        return str_replace(...);
    });
}

暗黙の拡張Implicit Extensions

バリデートする属性が存在していない場合か空文字列の場合、カスタム拡張したものも含め通常のバリデーションルールは実行されません。たとえばuniqueルールはnull値に対して実行されません。By default, when an attribute being validated is not present or contains an empty string, normal validation rules, including custom extensions, are not run. For example, the unique[#rule-unique] rule will not be run against an empty string:

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

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

Validator::make($input, $rules)->passes(); // true

属性が空であってもルールを実行するということは、その属性が必須であることを暗黙のうちに示しています。このような「暗黙の」拡張を作成するには、Validator::extendImplicit()メソッドを使います。For a rule to run even when an attribute is empty, the rule must imply that the attribute is required. To create such an "implicit" extension, use the Validator::extendImplicit() method:

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

Note: note 「暗黙の」拡張は、単にその属性が必須であるとほのめかしているだけです。属性が存在しない場合や空のときに、実際にバリデーションを失敗と判断するかどうかは、みなさん次第です。{note} An "implicit" extension only implies that the attribute is required. Whether it actually invalidates a missing or empty attribute is up to you.

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作