LoginSignup
2
1

More than 5 years have passed since last update.

Laravelのバリデーションエラーメッセージが文字化けした場合の解決方法

Last updated at Posted at 2019-04-02

バリデーションエラー時の日本語メッセージが文字化けする

適当にバリデーションを実装し、取得したエラーメッセージをChromeのコンソールログに出力してみます。


$validator = Validator::make($request, [
            'id' => 'require|integer',
            'name' => 'require|string',
        ], [
            'id.integer' => '不正なidです。',
            'name.string' => '不正な名前です。'
        ]);

if ($validator->fails()) {
  return Response::json(
    [
      'code' => 'ERROR_***'
      'errors' => $validator->getMessageBag()->toArray()
    ], 
    400,
  );
}

すると、下のように、エラーメッセージが文字化けしてしまいます。


# console.log
{
  "code" : "ERROR_***"
  "errors" : "\u5165\u529b\u5024\u304c\u4e0d\u6b63\u3067\u3059\u3002"
}

もう解決策

Response::json()の第4引数に、JSON_UNESCAPED_UNICODEを設定。


return Response::json(
    [
      'code' => 'ERROR_***'
      'errors' => $validator->getMessageBag()->toArray()
    ], 
    400,
    [],
    JSON_UNESCAPED_UNICODE,
  );

上記のように、定義済み定数(https://www.php.net/manual/ja/json.constants.php)を渡すことで、
unicodeで日本語をエスケープせずにそのまま返してくれるようです。


# console.log
{
  "code" : "ERROR_***"
  "errors" : "不正な名前です。"
}

まとめ

バリデーションとは関係なく、Response::jsonの仕様であった。
ちなみに、バリデーションエラーメッセージを


$validator->errors()->all(),

で取得して渡すと文字化けしない。
時間があるときに調べてみよう。

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