本教程详细介绍了如何在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的FormRequest提供了一种方便的方式来封装验证逻辑。当验证失败时,它会触发failedValidation方法,并注入一个包含错误信息的Validator实例。默认情况下,$validator->getMessageBag()->toArray()会根据当前应用的locale返回错误消息。为了同时获取多种语言的错误,我们需要在消息定义阶段就嵌入这些多语言信息。
实现多语言验证错误的关键在于重写FormRequest中的messages()方法。这个方法允许您为特定的验证规则和字段定义自定义的错误消息。不同于简单的字符串,我们可以为每个规则定义一个包含多语言键值对的数组。
以下是一个SystemUserStoreRequest的示例,展示了如何为email字段的required和unique规则定义en-CA和fr-CA两种语言的错误消息:
// app/Http/Requests/SystemUserStoreRequest.php
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()方法中:
关于翻译文件:
为了使上述代码正常工作,您需要在resources/lang目录下创建相应的语言文件,例如:
validation.php文件应包含标准验证规则的翻译,
而attributes.php(或portal.php)文件则应包含字段名的翻译。
示例 resources/lang/en-CA/attributes.php:
'Email Address',
'first_name' => 'First Name',
];示例 resources/lang/fr-CA/attributes.php:
'Adresse e-mail',
'first_name' => 'Prénom',
];现在,当SystemUserStoreRequest验证失败时,$validator->getMessageBag()->toArray()将返回一个包含我们定义的这种多语言结构(例如['email.required' => ['en-CA' => '...', 'fr-CA' => '...']])的数组。我们需要在ApiRequest(或直接在SystemUserStoreRequest中)重写的failedValidation方法中,将这个结构转换为我们期望的最终API响应格式。
假设您的ApiRequest基类如下:
// app/Http/Requests/ApiRequest.php
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方法中:
app/Http/Requests/ApiRequest.php (基类)
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 (具体的请求类)
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')],
# php
# laravel
# js
# json
# app
# ai
# 多语言
# 键值对
# red
# 关联数组
# 封装
# mail
# 字符串
# 接口
# Attribute
# http
# 您的
# 自定义
# 错误信息
# 是一个
# 字段名
# 遍历
# 重写
# 抛出
# 这是
相关文章:
如何在阿里云虚拟服务器快速搭建网站?
网站制作壁纸教程视频,电脑壁纸网站?
如何快速打造个性化非模板自助建站?
PHP正则匹配日期和时间(时间戳转换)的实例代码
建站之星多图banner生成与模板自定义指南
建站之星好吗?新手能否轻松上手建站?
建站之星安装后界面空白如何解决?
南宁网站建设制作定制,南宁网站建设可以定制吗?
建站之星安装后如何自定义网站颜色与字体?
建站之星后台管理:高效配置与模板优化提升用户体验
如何快速生成可下载的建站源码工具?
建站之星代理商如何保障技术支持与售后服务?
怎么制作一个起泡网,水泡粪全漏粪育肥舍冬季氨气超过25ppm,可以有哪些措施降低舍内氨气水平?
建站主机与服务器功能差异如何区分?
实例解析Array和String方法
如何获取PHP WAP自助建站系统源码?
如何用PHP快速搭建CMS系统?
制作销售网站教学视频,销售网站有哪些?
公司网站制作费用多少,为公司建立一个网站需要哪些费用?
建站之星代理如何获取技术支持?
在线ppt制作网站有哪些软件,如何把网页的内容做成ppt?
C++用Dijkstra(迪杰斯特拉)算法求最短路径
网站制作和推广的区别,想自己建立一个网站做推广,有什么快捷方法马上做好一个网站?
网站制作难吗安全吗,做一个网站需要多久时间?
制作网站的软件免费下载,免费制作app哪个平台好?
定制建站平台哪家好?企业官网搭建与快速建站方案推荐
c++怎么实现高并发下的无锁队列_c++ std::atomic原子变量与CAS操作【详解】
php8.4新语法match怎么用_php8.4match表达式替代switch【方法】
教程网站设计制作软件,怎么创建自己的一个网站?
制作网站公司那家好,网络公司是做什么的?
油猴 教程,油猴搜脚本为什么会网页无法显示?
公司网站建设制作费用,想建设一个属于自己的企业网站,该如何去做?
宝塔面板创建网站无法访问?如何快速排查修复?
网站按钮制作软件,如何实现网页中按钮的自动点击?
网站制作公司排行榜,抖音怎样做个人官方网站
如何用IIS7快速搭建并优化网站站点?
建站之星安装需要哪些步骤及注意事项?
制作无缝贴图网站有哪些,3dmax无缝贴图怎么调?
建站之星导航配置指南:自助建站与SEO优化全解析
建站上市公司网站建设方案与SEO优化服务定制指南
关于BootStrap modal 在IOS9中不能弹出的解决方法(IOS 9 bootstrap modal ios 9 noticework)
如何在IIS7中新建站点?详细步骤解析
宝塔新建站点为何无法访问?如何排查?
建站之星安装提示数据库无法连接如何解决?
公司门户网站制作流程,华为官网怎么做?
如何选择域名并搭建高效网站?
图片制作网站免费软件,有没有免费的网站或软件可以将图片批量转为A4大小的pdf?
常州自助建站:操作简便模板丰富,企业个人快速搭建网站
攀枝花网站建设,攀枝花营业执照网上怎么年审?
网站好制作吗知乎,网站开发好学吗?有什么技巧?
*请认真填写需求信息,我们会在24小时内与您取得联系。