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

Laravel 9邮件翻译不指定键前缀时无法按locale加载的问题

Laravel 验证邮件主题翻译需指定键前缀的问题解决

问题说明

修改Laravel自带的VerifyEmail通知类(路径:vendor/laravel/framework/src/Illuminate/Auth/Notifications/VerifyEmail.php)时,使用Lang::get('Verify Email Address')获取邮件主题翻译,发现必须加上messages.前缀(如Lang::get('messages.Verify Email Address'))才能正常读取/resources/lang/lt/messages.php中的立陶宛语翻译。即使将翻译内容放到/lang/lt下的messages.json、app.php、app.json等文件中,无前缀的调用方式依然无效,且config/app.php已正确设置locale为lt。

原因分析

  1. Laravel的Lang::get()方法,当使用无前缀键时,默认会从**app.php翻译文件**中查找对应键值;若翻译内容放在messages.php里,必须指定messages.前缀才能定位到该数组下的键。
  2. JSON翻译文件的匹配逻辑是:传递完整字符串作为键时,Laravel会去对应locale的JSON文件(如lt.json)中查找完全匹配的字符串键,如果之前的JSON文件内容格式错误或放置路径不对,也会导致无法读取。

解决方案

方案1:使用JSON翻译文件(无需键前缀)

  1. 在/resources/lang/目录下创建lt.json文件,内容如下:
{
    "Verify Email Address": "Patvirtinkite el. pašto adresą",
    "Please click the button below to verify your email address.": "Prašome paspausti ant žemiau paspaustos nuorodos šio el. pašto adreso patvirtinimui.",
    "If you did not create an account, no further action is required.": "Jei Jūs nekūrėte svetainėje sena.lt vartotojo, jokių veiksmų atlikti nereikia."
}
  1. 在验证邮件通知类中保持无前缀调用:
->subject(Lang::get('Verify Email Address'))

此时Laravel会自动从lt.json中匹配对应字符串的翻译。

方案2:使用PHP数组文件,适配键前缀规则

  • 若继续使用messages.php文件,必须在调用时加上messages.前缀:
->subject(Lang::get('messages.Verify Email Address'))
  • 若想使用无前缀调用,可将翻译内容复制到/resources/lang/lt/app.php中:
<?php

return [
    // 保留原有默认翻译,新增以下内容
    "Verify Email Address"=> "Patvirtinkite el. pašto adresą",
    "Please click the button below to verify your email address."=> "Prašome paspausti ant žemiau paspaustos nuorodos šio el. pašto adreso patvirtinimui.",
    "If you did not create an account, no further action is required."=> "Jei Jūs nekūrėte svetainėje sena.lt vartotojo, jokių veiksmų atlikti nereikia.",
];

这样Lang::get('Verify Email Address')就能直接从app.php中读取翻译。

重要提示

不要直接修改vendor目录下的核心文件,后续Laravel版本更新会覆盖这些修改。正确做法是自定义验证邮件通知类:

  1. 执行命令生成自定义通知:
php artisan make:notification CustomVerifyEmail
  1. 将vendor/laravel/framework/src/Illuminate/Auth/Notifications/VerifyEmail.php中的代码复制到新创建的CustomVerifyEmail类中,再做翻译修改。
  2. 在User模型中重写sendEmailVerificationNotification方法,替换为自定义通知:
public function sendEmailVerificationNotification()
{
    $this->notify(new \App\Notifications\CustomVerifyEmail);
}

内容的提问来源于stack exchange,提问作者Gediminas Šukys

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 19:39:57