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


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

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

在构建国际化的Web应用或API时,经常会遇到需要同时向客户端返回多种语言的验证错误信息。Lar*el的默认验证机制通常只返回当前应用语言环境下的错误消息。当需求是为每个字段的每个错误同时提供多种语言版本时,就需要对默认行为进行定制。本教程将指导您如何通过扩展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."
        ]
      }
  }
}

理解Lar*el验证与多语言需求

Lar*el的FormRequest提供了一种方便的方式来封装验证逻辑。当验证失败时,它会触发failedValidation方法,并注入一个包含错误信息的Validator实例。默认情况下,$validator->getMessageBag()->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. 我们使用Lar*el的__辅助函数来获取翻译字符串。
    • __('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)文件则应包含字段名的翻译。

6pen Art 6pen Art

AI绘画生成

6pen Art 213 查看详情 6pen Art

示例 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')],

以上就是Lar*el表单请求中同时返回多语言验证错误教程的详细内容,更多请关注php中文网其它相关文章!


# laravel  # js  # json  # app  # ai  # php  # 重写  # 合肥同城小程序营销推广  # 禅城百度推广网站代理  # 第三方推广营销方案设计  # 廊坊seo培训机构  # 杏坛网站推广方案  # 做网站建设与管理题库  # 永康网站建设优化排名  # 抖音营销推广创新案例  # 本地网站推广方法  # 石家庄推广营销软文设计  # 遍历  # 键值  # 字段名  # 表单  # 是一个  # 错误信息  # 自定义  # 您的  # red  # 键值对  # 多语言 


相关栏目: 【 Google疑问12 】 【 Facebook疑问10 】 【 优化推广96088 】 【 技术知识133117 】 【 IDC资讯59369 】 【 网络运营7196 】 【 IT资讯61894


相关推荐: word文档行距怎么调?word文档调行距的操作步骤  解决Pandas DataFrame高度碎片化警告:高效创建多列的策略  J*a中导出MySQL表为SQL脚本的两种方法  知音漫客官网首页入口_知音漫客热门漫画推荐  太平年在哪个平台播出  MongoDB聚合管道:高效统计列表中各项的文档数量  嘴唇干裂起皮怎么办 唇部护理与预防干裂的方法【详解】  基于键值条件高效映射 Pandas DataFrame 多列数据  Flexbox布局:实现粘性导航与底部页脚的完美结合  《盗墓笔记手游》技能介绍  美发店速赢秘籍  使用逻辑应用(Logic Apps)自动处理邮件附件中的XML到Excel  C++如何使用CMake构建项目_C++ CMakeLists.txt编写入门教程  Dash应用多值文本输入处理与类型转换教程  Win10显卡驱动安装失败怎么办 Win10使用DDU彻底卸载驱动【解决】  mysql如何限制远程访问_mysql远程访问限制方法  苹果如何下载nanobanana  《东方财富》条件单关闭方法  驱动人生:游戏修复指南  谷歌浏览器官网地址整理_谷歌浏览器新版直连2026稳定访问  Sublime怎么自动添加CSS前缀_Sublime安装Autoprefixer插件  j*a中ArrayBlockingQueue的使用  夸克浏览器资源嗅探怎么用 夸克浏览器网页资源下载技巧【教程】  Win10如何关闭开机锁屏界面_Windows10跳过锁屏直接登录设置  抖音网页版官方链接 抖音网页版官网链接入口  Safari浏览器自动填表功能失效怎么办 Safari表单管理修复  悟空浏览器网页版链接 悟空浏览器网页版最新有效地址  《偃武》甘宁技能详解  在VS Code中进行数据科学和机器学习开发  拷贝漫画2025网页版入口 拷贝漫画官网免费看全集  漫蛙漫画官方版直通入口 2025漫蛙漫画免注册访问说明  微博网页版访问入口 微博网页版网页端使用指南  如何在CSS中使用伪类选择器_hover实现悬停效果  深入理解Python对象引用与链表属性赋值  火狐浏览器无法自动更新怎么办 手动更新火狐浏览器到最新版本【解决】  《oppo商城》维修服务位置  《荔枝fm》导出文件教程  解决J*aScript动态图片上传中ID重复问题:在同一页面显示多张独立图片  vivo手机视频通话美颜怎么设置_vivo视频通话美颜开启方法  《sketchbook》选中部分图案移动方法  GBA模拟器手柄按键设置  TikTok视频播放中断怎么办 TikTok播放异常修复方法  百度网盘网页入口链接分享 百度网盘官网入口网页登录  电脑视频号|直播|如何分享屏幕  sublime怎么快速在浏览器中预览HTML_sublime配置View in Browser教程  excel怎么制作考勤表 excel考勤模板与函数公式讲解  c++如何使用std::thread::join和detach_c++线程生命周期管理  C++ optional用法详解_C++17处理可能为空的返回值  猫眼电影app怎么查询电影院的营业时间_猫眼电影影院营业时间查询教程  CSS绝对定位与溢出控制:实现背景元素局部显示不触发滚动条 

 2025-11-23

了解您产品搜索量及市场趋势,制定营销计划

同行竞争及网站分析保障您的广告效果

点击免费数据支持

提交您的需求,1小时内享受我们的专业解答。

运城市盐湖区信雨科技有限公司


运城市盐湖区信雨科技有限公司

运城市盐湖区信雨科技有限公司是一家深耕海外推广领域十年的专业服务商,作为谷歌推广与Facebook广告全球合作伙伴,聚焦外贸企业出海痛点,以数字化营销为核心,提供一站式海外营销解决方案。公司凭借十年行业沉淀与平台官方资源加持,打破传统外贸获客壁垒,助力企业高效开拓全球市场,成为中小企业出海的可靠合作伙伴。

 8156699

 13765294890

 8156699@qq.com

Notice

We and selected third parties use cookies or similar technologies for technical purposes and, with your consent, for other purposes as specified in the cookie policy.
You can consent to the use of such technologies by closing this notice, by interacting with any link or button outside of this notice or by continuing to browse otherwise.