如何在 laravel fortify 中显示自定义消息

How to display a custom message in laravel fortify

我正在尝试更改“照片不得大于 1024 KB”。来自 UpdateUserProfileInformation 文件

class UpdateUserProfileInformation implements UpdatesUserProfileInformation
{
  public function update($user, array $input)
    {
        Validator::make($input, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', Rule::unique('users')->ignore($user->id)],
            'photo' => ['nullable', 'mimes:jpg,jpeg,png', 'max:1024'],
        ])->validateWithBag('updateProfileInformation');

        if (isset($input['photo'])) {
            $user->updateProfilePhoto($input['photo']);
        }

        if ($input['email'] !== $user->email &&
            $user instanceof MustVerifyEmail) {
            $this->updateVerifiedUser($user, $input);
        } else {
            $user->forceFill([
                'name' => $input['name'],
                'email' => $input['email'],
            ])->save();
        }
    }
}

我想将该消息更改为“照片不得大于 1 MB”。

您可以在 Validator::make() 的第三个参数上设置自定义消息:

$messages = [
   'photo.max' => 'The photo must not be greater than 1 MB."',
];

Validator::make($input, [
    'name' => ['required', 'string', 'max:255'],
    'email' => ['required', 'email', 'max:255', Rule::unique('users')->ignore($user->id)],
    'photo' => ['nullable', 'mimes:jpg,jpeg,png', 'max:1024'],
], $messages)
   ->validateWithBag('updateProfileInformation');

您可以像这样使用自定义消息进行验证


$messages = [
   'photo.max' => 'The photo must not be greater than 1 MB."',
];

Validator::make($input, [
    'name' => ['required', 'string', 'max:255'],
    'email' => ['required', 'email', 'max:255', Rule::unique('users')->ignore($user->id)],
    'photo' => ['nullable', 'mimes:jpg,jpeg,png', 'max:1024'],
], $messages)
   ->validateWithBag('updateProfileInformation');
"
]
)->validateWithBag('updateProfileInformation');

或者更动态的可能是这样的

$maxSize=1024;
$messages = [
   'photo.max' => "The photo must not be greater than {$maxSize/1024} MB.",
];

Validator::make($input, [
    'name' => ['required', 'string', 'max:255'],
    'email' => ['required', 'email', 'max:255', Rule::unique('users')->ignore($user->id)],
    'photo' => ['nullable', 'mimes:jpg,jpeg,png', 'max:'.$maxSize],
], $messages)
   ->validateWithBag('updateProfileInformation');
"
]
)->validateWithBag('updateProfileInformation');