我如何在 Laravel 5.5 的 FormRequest 类中返回自定义响应?

2024-05-04

我正在制作一个 API,我想返回错误数组,其格式如下$validator->errors();当我通过手动方式验证请求时生成。但我无法操纵响应。我想找到正确的制作方法。

这可以在 Laravel 5.4 中通过formatErrors方法并包括Illuminate\Contracts\Validation\ValidatorFormRequest 类中的类,但对于 5.5 版本它不起作用。我不知道怎么做。

这是我的控制器:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\ProductRequest;
use Illuminate\Validation\Rule;
use App\Product;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(ProductRequest $request)
    {
        $products = Product::where('code', 'LIKE', '%'.$request->input('search').'%')
        ->where('name', 'LIKE', '%'.$request->input('search').'%')
        ->paginate(10);
        $products->withPath($request->fullUrl());
        return $products;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(ProductRequest $request)
    {
        $product = new Product($request->validated());
        $product->save();
        return response('', 201);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $product = Product::find($id);
        return response($product, 200);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(ProductRequest $request, $id)
    {
        $product = Product::find($id);
        $product->fill($request->validated());
        $product->save();
        return response('', 200);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $product = Product::find($id);
        $product->delete();
        return response('', 204);
    }
}

这是我的 FormRequest 类

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class ProductRequest 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()
    {
        switch($this->method())
        {
            case 'GET':
            {
                return [
                    'code' => 'string',
                    'name' => 'string',
                ];
            } break;
            case 'POST':
            {
                return [
                    'code' => 'required|unique:Products,code',
                    'name' => 'required',
                    'description' => 'required',
                    'quantity' => 'required|min:0',
                    'price' => 'required|numeric',
                    'extemp' => [
                        Rule::in(['tax', 'free']),
                    ]
                ];
            } break;
            case 'PUT':
            {
                return [
                    'code' => 'unique:products,code,'.$this->route('product'),
                    'name' => 'string:min:1',
                    'description' => 'string|min:1',
                    'quantity' => 'integer|min:0',
                    'price' => 'numeric',
                    'extemp' => [
                        Rule::in(['tax', 'free']),
                    ],
                ];
            } break;
            case 'PATCH': break;
            case 'DELETE': break;
            default:
            {
                return [];
            } break;
        }
    }

    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array
     */
    public function messages()
    {
        return [
            //Product
            'code.required' => 'El :attribute es obligatorio.',
            'code.unique' => 'El :attribute ya se encuentra registrado.',
            'name.required' => 'El :attribute es obligatorio.',
            'name.min' => 'El :attribute es obligatorio.',
            'description.required' => 'El :attribute es obligatorio.',
            'description.min' => 'El :attribute es obligatorio.',
            'quantity.required' => 'La :attribute es obligatoria.',
            'quantity.integer' => 'La :attribute debe ser un número entero.',
            'quantity.min' => 'La :attribute debe ser al menos :min.',
            'price.required' => 'El :attribute es obligatorio.',
            'price.numeric' => 'El :attribute debe ser un valor numérico.',
            'extemp.in' => 'El :attribute seleccionado es inválido.',
        ];
    }
    public function attributes(){
        return [
            'code' => 'código',
            'name' => 'nombre',
            'description' => 'descripción',
            'quantity' => 'cantidad',
            'price' => 'precio',
            'extemp' => 'exento',
        ];
    }
}

我的回应:

{
    "message": "The given data was invalid.",
    "errors": {
        "code": [
            "El código es obligatorio."
        ],
        "name": [
            "El nombre es obligatorio."
        ],
        "description": [
            "El descripción es obligatorio."
        ],
        "quantity": [
            "La cantidad es obligatoria."
        ],
        "price": [
            "El precio es obligatorio."
        ]
    }
}

我想要的回应 (with $validator->errors();)

[
    "El código es obligatorio.",
    "El nombre es obligatorio.",
    "El descripción es obligatorio.",
    "La cantidad es obligatoria.",
    "El precio es obligatorio."
]

你必须override the failedValidation()方法并发出异常并给出您想要的响应。 所以,你需要使用Illuminate\Contracts\Validation\Validator and Illuminate\Http\Exceptions\HttpResponseException在里面申请表类,并覆盖failedValidation() method:

protected function failedValidation(Validator $validator) { 
        throw new HttpResponseException(response()->json($validator->errors()->all(), 422)); 
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我如何在 Laravel 5.5 的 FormRequest 类中返回自定义响应? 的相关文章

随机推荐

  • 在 Spring 5 Webflux 中启用 CORS?

    如何启用CORS在 Spring 5 Webflux 项目中 我找不到任何合适的文档 我使用这个自定义过滤器取得了成功 import org springframework context annotation Bean import or
  • 在两个应用程序之间通过 url 方案快速传递数据?

    有两个测试应用程序称为发送者和接收者 他们通过 UrlScheme 相互通信 我想从发送者发送一个字符串到接收者 这可能吗 关于字符串的详细信息 我都在发送者和接收者中创建文本字段 我会在发送者文本字段上发送一些字符串 当我单击按钮时 字符
  • '||=' 运算符在 ruby​​ 中起什么作用? [复制]

    这个问题在这里已经有答案了 可能的重复 在 Ruby 中是什么意思 https stackoverflow com questions 995593 what does mean in ruby 我是红宝石新手 我看到这里的答案之一使用了它
  • 跨多个子域的 WebAuthn

    我正在尝试在我的网站上设置 WebAuthn 身份验证流程 但遇到了问题 我希望我的用户能够在主网站 www domain com 上注册他们的设备 以便可以通过用户设置轻松访问 身份验证本身通过 IdP sso domain com 在不
  • C 程序的“编译器正确”命令

    这是关于中提到的编译步骤Linux 期刊文章 https www linuxjournal com article 6463 C 程序是使用编译的cpp cc1 as and ld该文章中的命令 我能够执行这些步骤cpp as and ld
  • 一个好的 Java VM 中方法调用的开销是多少?

    有人可以提供反汇编的机器代码汇编程序列表吗 我的意思是 与 C 中的普通函数调用相比 肯定有一些开销 VM 需要跟踪调用以查找热点 并且当它使用编译代码时 如果新加载的类需要重新编译 它需要提供动态更改编译方法的方法 我想某处也有返回堆栈溢
  • 如何安装 php 5.3.14 ubuntu 12.10

    我必须在我的 ubuntu 12 10 上安装这个特定版本才能与提供商保持兼容 我可以使用 synaptic 轻松安装 php 5 3 10 但无法升级到 5 3 14 我怎样才能做到这一点 apt get 不起作用 我在网上看到了几个教程
  • 用户评级的 ER 模型

    我有很多 用户 每个用户最多有 5 个 服务 用户应该能够对每项服务进行评分 0 5 我还想保留用户的平均评分 这是我的想法 但是还有更好的方法吗 User id user name dob 服务 固定数量的服务 id service de
  • Swift - 以编程方式刷新约束

    我的 VC 开头为stackView附有Align Bottom to Safe Area 我有 tabBar 但一开始是隐藏的tabBar isHidden true 稍后 当 tabBar 出现时 它会隐藏stackView 所以我需要
  • 使用 Python 发布 XML 文件

    我是 Python 新手 需要一些帮助 我的目标是向 URL 发送一些带有 post 请求的 XML 这将触发发送 SMS 我有一个小的 XML 文档 我想将其发布到 URL 我可以在需要发布的 python 代码中引用我的服务器上的 XM
  • 如何从我自己的线程安全地修改 JavaFX GUI 节点?

    我尝试更改线程中的 JavaFX GUI 节点 但看到以下错误 线程 Thread 8 中的异常 java lang IllegalStateException 不存在 FX应用线程 当前线程 线程 8 生成错误的示例代码 public c
  • Android Firebase-Analytics:无法将 null 设置为 userid 和 userproperty

    我使用下面的代码片段通过设置 null 来清除 userid 和 userproperty 值 但该值保留在 GoogleAnalytics Firebase 中 FirebaseAnalytics getInstance context
  • IE8 中 JavaScript 日期未定义/NaN

    我用它来测试日期输入是否距今天的日期少于 7 天 它适用于除 IE9 之外的所有浏览器 var today new Date
  • Java 按日期作为字符串对列表 进行排序

    我有一个类型列表 我想按日期元素对该列表进行排序 我用谷歌搜索 看到了一些具有可比性的解决方案 但是是否有可能在不实现类中接口的情况下做到这一点 我的列表如下所示 列表 id 33 文本 test1 日期 06 02 15 id 81 文本
  • 如何在 jQuery 中获取会话中的值

    我是 jQuery 的初学者 我想在 HTML 页面中设置值 并且必须在另一个 HTML 页面中获取它们 这是我现在正在尝试的代码片段 要在会话中设置值 session set userName uname val 要从会话中获取值 ses
  • 如何在 Vim 中从命令行模式复制文本?

    比如说 我刚刚在 Vim 中运行了这个命令 nmap
  • mingw32-make 的目录更改错误

    我正在MinGW32下构建POCO库1 6 0 环境 Windows 7 Ultimate 32位 shell MSYS 执行成功 配置 configure Configured for MinGW config make的内容 POCO
  • 使用 SFML 绘制文本时出现段错误

    我做了一个Button应该绘制一些顶点和字符串的类RenderWindow 这是删除了不相关部分的代码 here http pastebin com 4a5RuS2y是完整的代码 namespace game class Button pu
  • 如何从 Selectize 中删除项目?

    有什么方法可以从 Selectize 中删除项目吗 这是我的示例列表 AMNT QTY NA 当我经过时NA它应该删除特定项目 fn removeSelectorValue function value var selectize this
  • 我如何在 Laravel 5.5 的 FormRequest 类中返回自定义响应?

    我正在制作一个 API 我想返回错误数组 其格式如下 validator gt errors 当我通过手动方式验证请求时生成 但我无法操纵响应 我想找到正确的制作方法 这可以在 Laravel 5 4 中通过formatErrors方法并包