自定义闪烁错误格式 - Laravel 5.3

时间:2016-09-16 04:53:39

标签: php laravel method-overriding laravel-validation laravel-5.3

我想自定义闪烁错误消息的格式,在我执行$this->validator($request->all())->validate();

之后收到的消息

对于ajax请求,它以:

响应
{
    "name": [
        "The name field is required."
    ],
    "email": [
        "The email field is required."
    ],
}

但我希望它看起来像

{
    "status": "fail",
    "errors": {
        "name": [
            "The name field is required."
        ],
        "email": [
            "The email field is required."
        ],
    }
}

我在自定义闪烁错误格式下阅读了documentation,并在我的formatValidationErrors课程中添加了Controller方法,但它没有任何区别。

public function formatValidationErrors(Validator $validator)
{
    return ['status' => 'fail', 'errors' => $validator->errors()->getMessages()];
}

即使我更改原始formatValidationErrors特征中的Illuminate\Foundation\Validation\ValidatesRequests方法,它也不会改变

我不得不在所有请求调用中构建此格式,因此存在代码重复。如果我可以拨打$this->validator($request->all())->validate()并根据我的要求自动格式化,那就太好了。

2 个答案:

答案 0 :(得分:0)

更改它的方法是创建一个扩展Validator并覆盖addError方法的类。这是一个示例代码:

<?php

namespace App\Validators;

use Illuminate\Support\MessageBag;
use Illuminate\Validation\Validator;

class RestValidator extends Validator {

    /**
     * Add an error message to the validator's collection of messages.
     *
     * @param  string  $attribute
     * @param  string  $rule
     * @param  array   $parameters
     * @return void
     */
    protected function addError($attribute, $rule, $parameters)
    {
        $message = $this->getMessage($attribute, $rule);

        $message = $this->doReplacements($message, $attribute, $rule, $parameters);

        $customMessage = new MessageBag();

        $customMessage->merge(['code' => strtolower($rule.'_rule_error')]);
        $customMessage->merge(['message' => $message]);

        $this->messages->add($attribute, $customMessage);
    }
}

现在您可以在控制器中构建验证,如下所示:

$rules = [
    // Your rules here
];

$attributes = [
    // The attributes you're checking here
];

$validator = Validator::make($attributes, $rules);

if ($validator->fails()) {
    $errorMessage = [
        'status' => 'fail',
        'errors' => $validator->errors()
    ];

    return $errorMessage;
}

// The rest of your code goes here

答案 1 :(得分:0)

在你的模型中试试这个,

public function response(array $errors)
{
    if (($this->ajax() && !$this->pjax()) || $this->wantsJson()) {
        $errors = array('status' => 'fail', 'errors' => $errors);
        return new JsonResponse($errors, 422);
    }
    return $this->redirector->to($this->getRedirectUrl())
        ->withInput($this->except($this->dontFlash))
        ->withErrors($errors, $this->errorBag);
}

它会按预期产生,

{
"status": "fail",
  "error": {
    "name": [
      "The name field is required."
    ],
    "email": [
      "The email field is required"
    ]
  }
}