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

Laravel翻译嵌套失效:如何让动态属性翻译生效?

Laravel验证翻译中__('strings.:attribute')失效的原因及解决方法

失效原因

  • 当你在validation.php中直接编写__('strings.:attribute')时,__()翻译函数会立即执行,此时:attribute是字面意义的字符串,而非验证阶段会被替换的属性占位符。系统会去lang/en/strings.php中查找键为:attribute的翻译项,而你并未定义该键,因此翻译失败,最终返回原始键名或默认值。
  • 手动测试__('strings.something')时,something是strings.php中实际存在的翻译键,因此能正常完成翻译。

解决方法

以下三种方案可按需选择:

1. 属性映射法(简单直接)

在validation.php中定义attributes数组,将属性名直接映射到对应的strings翻译项:

// App/resources/lang/en/validation.php
'attributes' => [
    'email' => __('strings.email'),
    'password' => __('strings.password'),
    // 添加其他需要翻译的属性
],

'different' => 'The attribute ":attribute" cannot be the same as the ":other" attribute',

验证器生成错误消息时,:attribute和:other会自动替换为对应的翻译内容。

2. 自定义替换器(灵活通用)

在AppServiceProvider的boot方法中添加验证规则的替换逻辑,自动将属性名转为strings中的翻译:

// App/Providers/AppServiceProvider.php
use Illuminate\Support\Facades\Validator;

public function boot()
{
    Validator::replacer('different', function ($message, $attribute, $rule, $parameters) {
        // 翻译当前属性和对比属性
        $transAttr = __('strings.' . $attribute);
        $transOther = __('strings.' . $parameters[0]);
        // 替换消息中的占位符
        return str_replace([':attribute', ':other'], [$transAttr, $transOther], $message);
    });
}

然后validation.php中的消息保持简洁:

'different' => 'The attribute ":attribute" cannot be the same as the ":other" attribute',

该方案无需逐个配置属性,所有使用different规则的属性都会自动完成翻译。

3. 手动替换消息(按需定制)

在验证逻辑中手动生成包含翻译的自定义消息,适合个别特殊场景:

$validator = Validator::make($request->all(), [
    'email' => 'different:password',
]);

$validator->setCustomMessages([
    'email.different' => __('validation.different', [
        'attribute' => __('strings.email'),
        'other' => __('strings.password'),
    ]),
]);

对应validation.php中需定义基础消息:

'different' => 'The attribute ":attribute" cannot be the same as the ":other" attribute',

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 11:20:33