dpict99695329 2017-12-18 13:09 采纳率: 100%
浏览 90
已采纳

Laravel自定义验证和ajax

The validation on my Laravel 4.2 project was done with Ardent package. After going to Laravel 5.5 I have eliminated Ardent and wanted to do Laravel's native validation with form requests.

The problem I have is that the Ajax call was validated before like this:

public function postRegisterAjax(A)
{
    try {
         ...
    } catch (ExceptionBag $e) {
        $msg = $e->getMessageBag()->all(':message');
        $status = Status::ERROR;
    }

    return $this->responseJson($status, $msg);
}

Now I introduced UserValidationRequest class and I would like Ajax call to throw me an error message without the need to reload the page. In order to do that, I need to forward status and message as Json response.

I somehow tried to do that with after validation hooks, but it doesn't work:

protected function getValidatorInstance()
{
    $validator = parent::getValidatorInstance();

    if ($validator->fails()) {
        \Log::info($validator->errors());

        $msg = $validator->errors();
        $status = Status::ERROR;

        return response()->json(['response' => [
            'status' => $status,
            'msg' => $msg,
        ]]);
    }

    return $validator;
}

The code fails on return response() saying that Method passes does not exist (Illuminate/Support/Traits/Macroable.php:96).

Does anyone know what seems to be the issue?

  • 写回答

1条回答 默认 最新

  • duanjiwei1283 2017-12-20 08:25
    关注

    From Laravel 5.x version (not sure), failedValidation() method was introduced in form requests instead of what Laravel 4.x had as response().

    I resolved my issue by tailoring the response to my needs by overriding that method in my form request:

    public function failedValidation(Validator $validator)
    {
        if ($validator->fails()) {
            $status = Status::ERROR;
            throw new HttpResponseException(response()->json(["response" => [
                'msg'    => $validator->errors()->all(':message'),
                'status' => $status
            ]]));
        }
    
        return response()->json(["response" => [
            'msg'    => 'User successfully registered',
            'status' => Status::SUCCESS
        ]]);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器