Laravelエラーメッセージの日本語化


Laravelのエラーメッセージを日本語化したい。
英語は苦手なので、こんなのが来ると諦めの気持ち多めになります。

Laravelの言語ファイル

Laravelには言語ファイルが標準であるそうです。ローカリゼーション機能というらしいです。
ここに言語ファイルがあります。

ただデフォルトではenしかありません。
このenフォルダを丸々コピーして、フォルダ名をjaに変え、langフォルダ内に置いておきます。

ロケール設定

resources/lang/ja/validation.php
|--------------------------------------------------------------------------
    | Application Locale Configuration
    |--------------------------------------------------------------------------
    |
    | The application locale determines the default locale that will be used
    | by the translation service provider. You are free to set this value
    | to any of the locales which will be supported by the application.
    |
    */

    'locale' => 'en',

    /*
    |--------------------------------------------------------------------------
    | Application Fallback Locale
    |--------------------------------------------------------------------------
    |
    | The fallback locale determines the locale to use when the current one
    | is not available. You may change the value to correspond to any of
    | the language folders that are provided through your application.
    |
    */

    'fallback_locale' => 'en',

上記の'locale' => 'en'を、
jaに変えます。

そして先ほどコピーしたファイルのvalidation.phpファイルを、力技で日本語にしていきます。


めっちゃ多い。まだある。
これを一つ一つ日本語化していくのは大変。

「この場合のこのバリデーションエラーの時にはこれを表示!」という時も変更可能だそうです。
公式ページにも書いてありました。

多くの場合、Validatorに直接カスタムメッセージを渡すよりは言語ファイルに指定したいですよね。ならば>resources/lang/xx/validation.php言語ファイルのcustom配列にメッセージを追加してください。

resources/lang/ja/validation.php
    |--------------------------------------------------------------------------
    | Custom Validation Language Lines
    |--------------------------------------------------------------------------
    |
    | Here you may specify custom validation messages for attributes using the
    | convention "attribute.rule" to name the lines. This makes it quick to
    | specify a specific custom language line for a given attribute rule.
    |
    */

    'custom' => [
        'attribute-name' => [
            'rule-name' => 'custom-message',
        ],
    ],

公式ページにはこんな感じで例が書いてあります。

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

これを参考に、試しにjaファイル内のvalidation.phpファイルのところに、こんな感じで書いてエラーを出してみます。配列のキーはinputタグのname属性っぽいです。

resources/lang/ja/validation.php
'custom' => [
        'email' => [
            'required' => 'メールアドレスを入力してください!',
            'email' => '正式なメールアドレスを入力してください!',
        ],
        'nickname' => [
            'required' => 'ユーザー名を入力してください!',
            'unique' => '入力されたユーザー名は既に使用されています!',
            ],
        'occupation' => [
            'required' => '職種を選択してください!',
            ],
    ],


なんか余計なものも混じってますが、引き続き日本語化はできそうなので、一応完了という事で。

今回はこちらのサイト様で勉強させていただきました。
Laravelのvalidationメソッドでバリデーションを実装する入門編(日本語エラーメッセージ付き)
Laravel 5.5 バリデーション
ありがとうございました。