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

时间:2017-09-20 14:57:07

标签: laravel laravel-validation laravel-5.5 laravel-request laravel-response

我正在创建一个API,我希望以我手动方式验证请求时$validator->errors();生成的格式返回错误数组。但我不能操纵回应。我想找到正确的方法来制作它。

这可以使用formatErrors方法在Laravel 5.4中完成,并在FormRequest类中包含Illuminate\Contracts\Validation\Validator类,但对于版本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);
    }
}

这是mi 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."
        ]
    }
}

响应我想要的内容(使用$validator->errors();

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

3 个答案:

答案 0 :(得分:10)

您必须覆盖 failedValidation()方法并使用您想要的响应发出异常。 因此,您需要在 RequestForm 类中使用Illuminate\Contracts\Validation\ValidatorIlluminate\Http\Exceptions\HttpResponseException,并覆盖failedValidation()方法:

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

答案 1 :(得分:1)

在我的情况下,我使用Laravel 7并做了一些改动:

//add depences
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Contracts\Validation\Validator;

//override this method in your FormRequest
protected function failedValidation(Validator $validator){
  throw new HttpResponseException(response()->json($validator->errors(), 422)); 
}

答案 2 :(得分:0)

为此,需要覆盖请求文件中的failedValidation()功能。

protected function failedValidation(Validator $validator)
{
    throw new HttpResponseException(response()->json([
      'errors' => $validator->errors(),
      'status' => false
    ], 422));
}

要使其use这些名称空间起作用:

对于laravel 5.4及更高版本:

 use Illuminate\Contracts\Validation\Validator;

 use Illuminate\Http\Exceptions\HttpResponseException;

description here

laravel 5.4以下:

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exception\HttpResponseException;

description here