0

0

Laravel表单请求中同时返回多语言验证错误教程

聖光之護

聖光之護

发布时间:2025-11-23 14:05:58

|

1046人浏览过

|

来源于php中文网

原创

Laravel表单请求中同时返回多语言验证错误教程

本教程详细介绍了如何在laravel应用程序中实现同时返回多种语言的验证错误。通过自定义`formrequest`的`messages()`方法来定义包含多语言信息的验证消息,并进一步在`failedvalidation`方法中处理这些信息,以生成符合特定多语言输出结构的api响应,从而满足复杂的多语言api接口需求。

在构建国际化的Web应用或API时,经常会遇到需要同时向客户端返回多种语言的验证错误信息。Laravel的默认验证机制通常只返回当前应用语言环境下的错误消息。当需求是为每个字段的每个错误同时提供多种语言版本时,就需要对默认行为进行定制。本教程将指导您如何通过扩展FormRequest类来实现这一目标,生成如以下结构的多语言验证错误响应:

{
  "detail": {
      "email": {
        "en-CA" : [
          "The email has already been taken."
        ],
        "fr-CA" : [
          "The french text."
        ]
      },
      "first_name": {
        "en-CA" : [
          "The first name must be at least 5.",
          "The first name must be an integer."
        ],
        "fr-CA" : [
          "The french text",
          "The french text."
        ]
      }
  }
}

理解Laravel验证与多语言需求

Laravel的FormRequest提供了一种方便的方式来封装验证逻辑。当验证失败时,它会触发failedValidation方法,并注入一个包含错误信息的Validator实例。默认情况下,$validator-youjiankuohaophpcngetMessageBag()->toArray()会根据当前应用的locale返回错误消息。为了同时获取多种语言的错误,我们需要在消息定义阶段就嵌入这些多语言信息。

核心策略:定制FormRequest的messages()方法

实现多语言验证错误的关键在于重写FormRequest中的messages()方法。这个方法允许您为特定的验证规则和字段定义自定义的错误消息。不同于简单的字符串,我们可以为每个规则定义一个包含多语言键值对的数组。

以下是一个SystemUserStoreRequest的示例,展示了如何为email字段的required和unique规则定义en-CA和fr-CA两种语言的错误消息:

// app/Http/Requests/SystemUserStoreRequest.php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator; // 引入 Validator 类
use Illuminate\Http\Exceptions\HttpResponseException; // 引入 HttpResponseException

// 假设 ApiRequest 是您的基类 FormRequest,其中重写了 failedValidation
class SystemUserStoreRequest extends ApiRequest // 或者直接 extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true; // 根据您的业务逻辑调整授权
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        // 假设 $this->id 用于在更新时排除当前用户
        $userId = $this->route('user') ? $this->route('user')->id : null;
        return [
            'email'      => 'required|email|unique:users,email,' . $userId,
            'first_name' => 'required|string|min:5',
            // ... 其他验证规则
        ];
    }

    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'email.required' => [
               'en-CA' => __('validation.required', ['attribute' => __('attributes.email', [], 'en-CA')], 'en-CA'),
               'fr-CA' => __('validation.required', ['attribute' => __('attributes.email', [], 'fr-CA')], 'fr-CA'),
            ],
            'email.email' => [
               'en-CA' => __('validation.email', ['attribute' => __('attributes.email', [], 'en-CA')], 'en-CA'),
               'fr-CA' => __('validation.email', ['attribute' => __('attributes.email', [], 'fr-CA')], 'fr-CA'),
            ],
            'email.unique' => [
               'en-CA' => __('validation.unique', ['attribute' => __('attributes.email', [], 'en-CA')], 'en-CA'),
               'fr-CA' => __('validation.unique', ['attribute' => __('attributes.email', [], 'fr-CA')], 'fr-CA'),
            ],
            'first_name.required' => [
                'en-CA' => __('validation.required', ['attribute' => __('attributes.first_name', [], 'en-CA')], 'en-CA'),
                'fr-CA' => __('validation.required', ['attribute' => __('attributes.first_name', [], 'fr-CA')], 'fr-CA'),
            ],
            'first_name.min' => [
                'en-CA' => __('validation.min.string', ['attribute' => __('attributes.first_name', [], 'en-CA'), 'min' => 5], 'en-CA'),
                'fr-CA' => __('validation.min.string', ['attribute' => __('attributes.first_name', [], 'fr-CA'), 'min' => 5], 'fr-CA'),
            ],
            // ... 其他字段和规则的多语言消息
        ];
    }
}

在上面的messages()方法中:

  1. 我们为每个验证规则(如email.required)返回一个关联数组。
  2. 这个数组的键是语言环境代码(例如en-CA, fr-CA),值是对应语言的错误消息。
  3. 我们使用Laravel的__辅助函数来获取翻译字符串。
    • __('validation.required', ['attribute' => ...], 'en-CA'):这会从lang/en-CA/validation.php文件中获取required规则的翻译。
    • ['attribute' => __('attributes.email', [], 'en-CA')]:这是关键!它解决了占位符替换的问题。我们通过再次调用__辅助函数来翻译:attribute占位符本身(例如,将email翻译成"Email Address"或"Adresse e-mail"),并指定目标语言。
    • attributes.email表示从lang/en-CA/attributes.php(或您自定义的翻译文件,如portal.php)中获取email字段的翻译。

关于翻译文件:

为了使上述代码正常工作,您需要在resources/lang目录下创建相应的语言文件,例如:

  • resources/lang/en-CA/validation.php
  • resources/lang/fr-CA/validation.php
  • resources/lang/en-CA/attributes.php (或 portal.php)
  • resources/lang/fr-CA/attributes.php (或 portal.php)

validation.php文件应包含标准验证规则的翻译,而attributes.php(或portal.php)文件则应包含字段名的翻译。

Rose.ai
Rose.ai

一个云数据平台,帮助用户发现、可视化数据

下载

示例 resources/lang/en-CA/attributes.php:

<?php

return [
    'email' => 'Email Address',
    'first_name' => 'First Name',
];

示例 resources/lang/fr-CA/attributes.php:

<?php

return [
    'email' => 'Adresse e-mail',
    'first_name' => 'Prénom',
];

在failedValidation中构建多语言响应结构

现在,当SystemUserStoreRequest验证失败时,$validator->getMessageBag()->toArray()将返回一个包含我们定义的这种多语言结构(例如['email.required' => ['en-CA' => '...', 'fr-CA' => '...']])的数组。我们需要在ApiRequest(或直接在SystemUserStoreRequest中)重写的failedValidation方法中,将这个结构转换为我们期望的最终API响应格式。

假设您的ApiRequest基类如下:

// app/Http/Requests/ApiRequest.php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

abstract class ApiRequest extends FormRequest
{
    /**
     * Handle a failed validation attempt.
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @return void
     *
     * @throws \Illuminate\Http\Exceptions\HttpResponseException
     */
    protected function failedValidation(Validator $validator)
    {
        // 获取原始错误信息,现在它包含了多语言结构
        $rawErrors = $validator->getMessageBag()->toArray();
        $transformedErrors = [];

        foreach ($rawErrors as $fieldRule => $messages) {
            // $fieldRule 可能是 "email.required", "first_name.min" 等
            // $messages 是一个包含多语言消息的数组,例如:
            // [0 => ['en-CA' => '...', 'fr-CA' => '...']]

            // 提取字段名,例如从 "email.required" 中获取 "email"
            $field = explode('.', $fieldRule)[0];

            foreach ($messages as $messageItem) {
                // $messageItem 现在是 ['en-CA' => '...', 'fr-CA' => '...']
                foreach ($messageItem as $locale => $message) {
                    if (!isset($transformedErrors[$field])) {
                        $transformedErrors[$field] = [];
                    }
                    if (!isset($transformedErrors[$field][$locale])) {
                        $transformedErrors[$field][$locale] = [];
                    }
                    $transformedErrors[$field][$locale][] = $message;
                }
            }
        }

        // 抛出包含自定义响应的 HttpResponseException
        throw new HttpResponseException(response()->json([
            'message' => 'The given data was invalid.',
            'detail' => $transformedErrors,
        ], 422));
    }
}

在上述failedValidation方法中:

  1. 我们首先通过$validator->getMessageBag()->toArray()获取包含多语言信息的原始错误数组。
  2. 然后,我们遍历这个rawErrors数组。$fieldRule会是email.required、first_name.min等,而$messages则是一个包含多语言消息的数组(例如[0 => ['en-CA' => '...', 'fr-CA' => '...']])。
  3. 我们从$fieldRule中解析出实际的字段名(例如email)。
  4. 接着,我们再次遍历$messages数组,处理每个语言环境的消息,并将其添加到$transformedErrors中,构建出期望的嵌套结构。
  5. 最后,我们抛出一个HttpResponseException,其中包含自定义的JSON响应,其detail字段就是我们精心构造的多语言错误信息。

完整代码示例

app/Http/Requests/ApiRequest.php (基类)

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

abstract class ApiRequest extends FormRequest
{
    protected function failedValidation(Validator $validator)
    {
        $rawErrors = $validator->getMessageBag()->toArray();
        $transformedErrors = [];

        foreach ($rawErrors as $fieldRule => $messages) {
            $field = explode('.', $fieldRule)[0]; // 提取字段名

            foreach ($messages as $messageItem) {
                foreach ($messageItem as $locale => $message) {
                    if (!isset($transformedErrors[$field])) {
                        $transformedErrors[$field] = [];
                    }
                    if (!isset($transformedErrors[$field][$locale])) {
                        $transformedErrors[$field][$locale] = [];
                    }
                    $transformedErrors[$field][$locale][] = $message;
                }
            }
        }

        throw new HttpResponseException(response()->json([
            'message' => 'The given data was invalid.',
            'detail' => $transformedErrors,
        ], 422));
    }
}

app/Http/Requests/SystemUserStoreRequest.php (具体的请求类)

<?php

namespace App\Http\Requests;

use App\Http\Requests\ApiRequest; // 确保引入您的基类

class SystemUserStoreRequest extends ApiRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        $userId = $this->route('user') ? $this->route('user')->id : null;
        return [
            'email'      => 'required|email|unique:users,email,' . $userId,
            'first_name' => 'required|string|min:5',
        ];
    }

    public function messages()
    {
        return [
            'email.required' => [
               'en-CA' => __('validation.required', ['attribute' => __('attributes.email', [], 'en-CA')], 'en-CA'),
               'fr-CA' => __('validation.required', ['attribute' => __('attributes.email', [], 'fr-CA')],

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
laravel组件介绍
laravel组件介绍

laravel 提供了丰富的组件,包括身份验证、模板引擎、缓存、命令行工具、数据库交互、对象关系映射器、事件处理、文件操作、电子邮件发送、队列管理和数据验证。想了解更多laravel的相关内容,可以阅读本专题下面的文章。

340

2024.04.09

laravel中间件介绍
laravel中间件介绍

laravel 中间件分为五种类型:全局、路由、组、终止和自定。想了解更多laravel中间件的相关内容,可以阅读本专题下面的文章。

293

2024.04.09

laravel使用的设计模式有哪些
laravel使用的设计模式有哪些

laravel使用的设计模式有:1、单例模式;2、工厂方法模式;3、建造者模式;4、适配器模式;5、装饰器模式;6、策略模式;7、观察者模式。想了解更多laravel的相关内容,可以阅读本专题下面的文章。

773

2024.04.09

thinkphp和laravel哪个简单
thinkphp和laravel哪个简单

对于初学者来说,laravel 的入门门槛较低,更易上手,原因包括:1. 更简单的安装和配置;2. 丰富的文档和社区支持;3. 简洁易懂的语法和 api;4. 平缓的学习曲线。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

385

2024.04.10

laravel入门教程
laravel入门教程

本专题整合了laravel入门教程,想了解更多详细内容,请阅读专题下面的文章。

141

2025.08.05

laravel实战教程
laravel实战教程

本专题整合了laravel实战教程,阅读专题下面的文章了解更多详细内容。

85

2025.08.05

laravel面试题
laravel面试题

本专题整合了laravel面试题相关内容,阅读专题下面的文章了解更多详细内容。

80

2025.08.05

PHP高性能API设计与Laravel服务架构实践
PHP高性能API设计与Laravel服务架构实践

本专题围绕 PHP 在现代 Web 后端开发中的高性能实践展开,重点讲解基于 Laravel 框架构建可扩展 API 服务的核心方法。内容涵盖路由与中间件机制、服务容器与依赖注入、接口版本管理、缓存策略设计以及队列异步处理方案。同时结合高并发场景,深入分析性能瓶颈定位与优化思路,帮助开发者构建稳定、高效、易维护的 PHP 后端服务体系。

531

2026.03.04

TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

26

2026.03.13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
PHP课程
PHP课程

共137课时 | 13.5万人学习

JavaScript ES5基础线上课程教学
JavaScript ES5基础线上课程教学

共6课时 | 11.3万人学习

PHP新手语法线上课程教学
PHP新手语法线上课程教学

共13课时 | 1.0万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号