2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravelのバリデーションメッセージを日本語化する

Last updated at Posted at 2023-06-28

1. はじめに

バリデーションエラー時のメッセージはデフォルトでは英語となっています。
このメッセージを日本語にする方法はいくつかありますが、今回はLaravelプロジェクトにlaravel-lang/commonパッケージを追加して日本語化する方法を解説します。このパッケージは、Laravelのバリデーションメッセージなどの多言語ファイルを提供してくれます。

2. 対象読者

  • Laravelで開発を行っている方
  • 日本語(もしくは多言語)対応したい方
  • laravel-lang/commonパッケージの導入方法を知りたい方

3. 目次

4. 環境

  • PHP 8.2
  • Laravel 9.19

Dockerfile及びcomposer.jsonは下記です。

FROM php:8.2-fpm

RUN apt-get update \
    && apt-get upgrade -y \
    && apt-get install -y unzip libzip-dev libicu-dev

RUN docker-php-ext-install pdo_mysql zip
RUN docker-php-ext-enable pdo_mysql zip
RUN docker-php-ext-install pdo_mysql
RUN docker-php-ext-enable pdo_mysql
RUN docker-php-ext-configure intl
RUN docker-php-ext-install intl

RUN curl -sL https://deb.nodesource.com/setup_18.x | bash -
RUN apt-get install -y nodejs

COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

ENV COMPOSER_ALLOW_SUPERUSER=1
ENV COMPOSER_HOME /composer
ENV PATH $PATH:/composer/vendor/bin

RUN rm -rf /var/www/html
COPY ./api /var/www/api/
WORKDIR /var/www/api
RUN chmod -R a+w storage bootstrap/cache public
RUN composer install

EXPOSE 80
{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "require": {
        "php": "^8.2.0",
        "guzzlehttp/guzzle": "^7.2",
        "laravel/framework": "^9.19",
        "laravel/sanctum": "^3.0",
        "laravel/tinker": "^2.7",
    },
    "require-dev": {
        "barryvdh/laravel-ide-helper": "^2.13",
        "fakerphp/faker": "^1.9.1",
        "laravel/pint": "^1.0",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.4",
        "nunomaduro/collision": "^6.1",
        "nunomaduro/larastan": "^2.0",
        "phpunit/phpunit": "^9.5.10",
        "spatie/laravel-ignition": "^1.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-update-cmd": [
            "@php artisan vendor:publish --tag=laravel-assets --ansi --force"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true,
        "allow-plugins": {
            "pestphp/pest-plugin": true
        }
    },
    "minimum-stability": "stable",
    "prefer-stable": true
}

5. 本編

5-1. パッケージのインストール

laravel-lang/commonパッケージをインストールする方法は簡単です。
下記のコマンドで正常にインストールできた方は、5-2,5-3を飛ばしてください。

$ composer require laravel-lang/common --dev

5-2. laravel-langパッケージをインストールするための準備

私の環境の場合、下記のエラーが出力されました。

./composer.json has been updated
Running composer update laravel-lang/common
Loading composer repositories with package information
Info from https://repo.packagist.org: #StandWithUkraine
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - laravel-lang/common v1.0.0 requires laravel-lang/publisher ^12.0 -> satisfiable by laravel-lang/publisher[v12.0.0, v12.1.0, v12.2.0, v12.2.1].
    - laravel-lang/common[v3.0.0, ..., v3.1.1] require laravel-lang/publisher ^14.0 -> satisfiable by laravel-lang/publisher[v14.0.0, ..., v14.6.4].
    - laravel-lang/common v2.0.0 requires laravel-lang/publisher ^13.0 -> satisfiable by laravel-lang/publisher[v13.0.0, v13.0.1].
    - laravel-lang/publisher[v12.1.0, ..., v12.2.1] require dragon-code/support ^5.6 -> satisfiable by dragon-code/support[v5.6.1, ..., v5.8.1].
    - laravel-lang/publisher[v14.1.0, ..., v14.6.4] require dragon-code/support ^6.3 -> satisfiable by dragon-code/support[v6.3.0, ..., v6.11.2].
    - laravel-lang/publisher[v13.0.0, ..., v13.0.1] require dragon-code/support ^6.1.1 -> satisfiable by dragon-code/support[v6.1.1, ..., v6.11.2].
    - laravel-lang/publisher v12.0.0 requires illuminate/console ^7.0 || ^8.0 -> found illuminate/console[v7.0.0, ..., v7.30.6, v8.0.0, ..., v8.83.27] but these were not loaded, likely because it conflicts with another require.
    - dragon-code/support[v5.6.1, ..., v5.8.1] require psr/http-message ^1.0.1 -> found psr/http-message[1.0.1, 1.1] but the package is fixed to 2.0 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.
    - dragon-code/support[v6.0.1, ..., v6.11.2] require ext-bcmath * -> it is missing from your system. Install or enable PHP's bcmath extension.
    - Root composer.json requires laravel-lang/common * -> satisfiable by laravel-lang/common[v1.0.0, v2.0.0, v3.0.0, v3.1.0, v3.1.1].

To enable extensions, verify that they are enabled in your .ini files:
    - /usr/local/etc/php/conf.d/docker-fpm.ini
    - /usr/local/etc/php/conf.d/docker-php-ext-intl.ini
    - /usr/local/etc/php/conf.d/docker-php-ext-pdo_mysql.ini
    - /usr/local/etc/php/conf.d/docker-php-ext-sodium.ini
    - /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
    - /usr/local/etc/php/conf.d/docker-php-ext-zip.ini
You can also run `php --ini` in a terminal to see which files are used by PHP in CLI mode.
Alternatively, you can run Composer with `--ignore-platform-req=ext-bcmath` to temporarily ignore these required extensions.

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

エラーから、bcmath拡張モジュールが必要なことが分かります。
bcmathは任意精度数学関数と呼ばれる機能を持っています。

5-3. bcmathの有効化

DockerfileRUN docker-php-ext-install bcmathを追記し、コンテナを再起動します。

$ docker-compose up -d --build

再起動後、5-1に記載の方法でlaravel-lang/commonをインストールします。

5-4. 日本語ファイルの追加

下記のコマンドで言語ファイルを追加できます。

$ php artisan lang:add ja

  ja/validation.php ........................................................................................ 24ms DONE
  ja/http-statuses.php ...................................................................................... 6ms DONE
  ja.json ................................................................................................... 1ms DONE
  ja/auth.php ............................................................................................... 1ms DONE
  ja/pagination.php ......................................................................................... 1ms DONE
  ja/passwords.php .......................................................................................... 2ms DONE

言語ファイルを追加後、config/app.phplocaleを編集し、日本語に設定します。

// app.php
'locale' => 'ja', // デフォルトは'en'

5-5. 動作確認

以上の手順で、バリデーションエラー時に日本語を返す準備ができました。
例えば、メールアドレスのemailバリデーションの場合、下記のようになります。

// 英語の場合
{
    "message": "The email must be a valid email address.",
    "errors": {
        "email": [
            "The email must be a valid email address."
        ]
    }
}

// 日本語の場合
{
    "message": "Eメールは、有効なメールアドレス形式で指定してください。",
    "errors": {
        "email": [
            "Eメールは、有効なメールアドレス形式で指定してください。"
        ]
    }
}

6. さいごに

今回は、laravel-lang/commonパッケージを追加して、日本語ファイルを作成する方法を紹介しました。もちろん、手動でja/validation.phpを作成しても日本語対応できますが、パッケージをインストールした方が素早く作成できると思います。laravel-lang/commonの公式サイトでは他にも機能が紹介されていますので、一度確認していただければと思います。

7. 参考

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?