【问题标题】:Laravel custom form requests not validatingLaravel 自定义表单请求未验证
【发布时间】:2018-05-01 18:28:16
【问题描述】:

我在laravel 5.6 中创建了一个自定义表单请求,如下所示:

<?php

namespace Noetic\Plugins\blog\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StorePostRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [

        ];
    }
}

当我没有在规则中放置任何东西时,我让控制器工作,当我在其中放置任何规则时,假设我放置了

return [
    'title' =>  'required',
    'body'  =>  'required',
];

它一直有效,直到它被验证为真,我的意思是如果标题和正文通过了它就会得到验证,但是当我没有为标题或正文发送任何数据时,我没有收到错误作为响应,我看到了主页属于网络中间件,我想返回错误数据作为响应。

我的控制器是这样的:

public function store( StorePostRequest $request )
{
    if ($request->fails()) {
        return $this->errorResponse($request->errors()->all());
    }

    $data = $request->only('title', 'body');

    $post = Post::create($data);

    return response()->json(['post'=> $post ],200);
}

帮我解决这些问题。谢谢

【问题讨论】:

  • StorePostRequest 将自动验证并发送错误响应,您无需执行$request-&gt;fails()Check this.
  • @TheAlpha 是的,我知道,我也试过不使用这些,但它没有按预期工作。
  • 您如何发送ajax 请求?如果您发送ajax 请求,那么Laravel 会将错误作为json 发送,否则您将收到重定向响应。因此,请确保您正确发送请求,以便Laravel 可以确定它应该发送的响应类型。
  • 您需要发送一个accept 标头,即:Accept: application/json
  • @TheAlpha 是的,谢谢。

标签: php laravel laravel-5.6 laravel-request laravel-response


【解决方案1】:

在您的控制器功能中,您无需捕获验证,只需尝试成功路径即可。

Handler 将处理您的验证

public function store( StorePostRequest $request )
{
    $data = $request->only('title', 'body');

    $post = Post::create($data);

    return response()->json(['post'=> $post ],200);
}

在你的处理程序中

use Illuminate\Validation\ValidationException;

if ($exception instanceof ValidationException)
{
    return response($exception->errors())->header('Content-Type', 'application/json');
}

【讨论】:

    【解决方案2】:

    使用 Illuminate\Contracts\Validation\Validator;

    使用 Illuminate\Http\Exceptions\HttpResponseException;

    之后

    protected function failedValidation(Validator $validator) {
        throw new HttpResponseException(response()->json($validator->errors(), 422));
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-30
      • 2017-12-06
      • 2020-07-28
      • 2019-11-27
      • 2017-11-17
      • 2023-03-29
      • 2016-09-02
      • 2019-10-07
      相关资源
      最近更新 更多