Laravel 9验证自定义消息标题

w41d8nur  于 2023-02-17  发布在  其他
关注(0)|答案(2)|浏览(125)

当您像这样验证用户输入时:

$request->validate([
    'ref' => 'required',
    'name' => 'required'
]);

您可以自定义字段的错误消息:

$request->validate([
    'ref' => 'required',
    'name' => 'required'
], [
    'ref.required' => 'Custom Message for This Field',
    'name.required' => 'Custom Message for This Field'
]);

而结果会是这样的:

{
    "message": "Custom Message for This Field (and 1 more error).",
    "errors": {
        "ref": [
            "Custom Message for This Field"
        ],
        "name": [
            "Custom Message for This Field"
        ]
    }
}

但是我这里需要的是定制"message": "Custom Message for This Field (and 1 more error).",我该怎么做呢?

lrl1mhuk

lrl1mhuk1#

我认为你应该加上以下内容
/app/Exceptions/Handler.php
它将按照你的要求工作

/**
     * Render errors
     * @param \Illuminate\Http\Request $request
     * @param Throwable                $exception
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     * @throws \Throwable
     */
    public function render($request, Throwable $exception): \Illuminate\Http\Response|\Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
        {
            if ($exception instanceof ValidationException) {
                $messages = $exception->validator->errors()->all();
    
                if (!count($messages) || !is_string($messages[0])) {
                    return $exception->validator->getTranslator()->get(__('validation.invalid_data'));
                }
    
                $message = array_shift($messages);
    
                if ($count = count($messages)) {
                    $pluralized = $count === 1 ? 'error' : 'errors';
    
                    $message .= ' ' . $exception->validator->getTranslator()->get(__('validation.more_errors', ['count' => $count, 'pluralized' => $pluralized]));
                }
    
                return response()->json([
                    'errors' => $exception->validator->getMessageBag(),
                    'message' => $message
                ]);
            }
    
            return parent::render($request, $exception);
        }

祝你好运!

myss37ts

myss37ts2#

you may be override input key name 

"name": [
            "Custom Message for This Field"
        ]

lang/en/validation.php

'attributes' => [
        'name' => 'custom name'
    ]

相关问题