You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel 8中翻译多图片数组的动态验证错误信息为丹麦语

实现步骤

1. 新增多语言验证提示

在resources/lang目录下对应语言包的validation.php文件中,添加针对banner数组的自定义验证消息:

  • 丹麦语(da/validation.php)
return [
    // 其他原有翻译项
    'banners.*.dimensions' => 'De bannere::index har ugyldige billeddimensioner.',
];
  • 英语(en/validation.php)
return [
    // 其他原有翻译项
    'banners.*.dimensions' => 'Banner :index has invalid image dimensions.',
];

2. 注册全局占位符替换逻辑

在app/Providers/AppServiceProvider.php的boot方法中,注册验证器占位符替换逻辑,自动提取数组索引替换到提示语中:

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // 替换dimensions规则的:index占位符
        Validator::replacer('dimensions', function ($message, $attribute, $rule, $parameters) {
            if (str_contains($attribute, '.')) {
                $attributeSegments = explode('.', $attribute);
                $arrayIndex = end($attributeSegments);
                return str_replace(':index', $arrayIndex, $message);
            }
            return $message;
        });
    }
}

3. 正常编写数组验证规则

直接按Laravel数组验证规则写法编写校验逻辑即可,无需额外修改:

$validated = $request->validate([
    'banners' => 'required|array|min:1',
    'banners.*' => 'required|image|dimensions:min_width=1200,min_height=600', // 按实际需求调整尺寸参数
]);

后续切换站点语言时,验证错误信息会自动适配当前语言,同时自动填充出错的数组下标。

如果其他验证规则也需要用到数组下标占位符,只需按照上述格式新增对应规则的replacer即可。

内容的提问来源于stack exchange,提问作者Muhammad Kamran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 07:27:02