在我的模型中,我使用beforeafter为日期字段定义了一些验证规则:

'birth_date' => 'required|date|before:today|after:01-jan-1920',
'another_date' => 'required|date|before:tomorrow|after:01-jan-1990',

The validation works fine, however I can't figure out how to translate the strings today and tomorrow on the validation message.

In the validation.php language file the after and before messages are localizable, however the :date part of the message is still displaying the English version for today and tomorrow.

"after"            => "The :attribute must be a date after :date.",
"before"           => "The :attribute must be a date before :date.",

How could I localize those two words - today and tomorrow - in the validation message?

推荐答案

In short, add following code into resources/lang/whichever/validation.php

'values' => [
    // or whatever fields you wanna translate
    'birth_date' => [
        // or tomorrow
        'today' => '今天'
    ]
]

Explained:

https://github.com/laravel/framework/blob/7.x/src/Illuminate/Validation/Concerns/FormatsMessages.php#L319

/**
 * Get the displayable name of the value.
 *
 * @param  string  $attribute
 * @param  mixed  $value
 * @return string
 */
public function getDisplayableValue($attribute, $value)
{
    if (isset($this->customValues[$attribute][$value])) {
        return $this->customValues[$attribute][$value];
    }

    // the key we want
    $key = "validation.values.{$attribute}.{$value}";

    // if the translate found, then use it
    if (($line = $this->translator->get($key)) !== $key) {
        return $line;
    }

    if (is_bool($value)) {
        return $value ? 'true' : 'false';
    }

    return $value;
}

Laravel相关问答推荐

laravel如何在Blade 模板中将元素添加到数组

如何在 Laravel 中将 Select 选项表单插入数据库

在 Laravel 包中的路由上使用显式或隐式模型绑定

Laravel 集合排序不生效

使用命令行界面停止 laravel 服务器

Laravel Auth::attempt() 返回 false

laravel:如何在 Eloquent Query 中使用 LOWERCASE 函数?

Laravel 路由将变量传递给控制器

为什么人们将 .env 放入 gitignore?

用 laravel 表单确认删除?

函数 mcrypt_get_iv_size() 在 Laravel 4 上已弃用

计算laravel中查询返回的行数

Laravel 控制器构造

如何从不是控制器方法的方法发送响应?

Auth 在 Laravel Tinker 中不起作用

如何使用命令行手动运行 laravel/lumen 作业(job)

Lumen/Laravel 6:调用未定义的函数 array_except()

Laravel - 使用 Eloquent 查询构建器在 Select 中添加自定义列

Laravel 4 - 文件上传

Laravel 4:分析器在哪里?