使用Ajax对Laravel 5.5 FormRequest进行验证

时间:2017-11-02 11:19:45

标签: ajax laravel response laravel-5.5

FormRequest与Laravel 5.4配合得很好,但在Laravel 5.5上显示400 (Bad Request)

这是我的代码:

  

这是CategoryRequest Class

<?php

namespace App\Domain\Category\Request;


use App\Http\Requests\FormRequest;
use App\Http\Requests\JsonRequest;

class CategoryRequest extends JsonRequest
{
    /**
     * 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 [
            'category' => 'required',
            'status' => 'required'
        ];
    }
}

我将它扩展到JsonRequest类,我曾经在Laravel 5.4中使用它并且以前正常工作。

  

这是JsonRequest Class

<?php

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;

class JsonRequest extends FormRequest
{
    public function failedValidation(Validator $validator)
    {
    $errors = (new ValidationException($validator))->errors();

    throw new HttpResponseException(response()->json([
        'success' => false,
        'errors' => $errors,
    ], JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
   }
}

但是对于laravel 5.5来说它现在还不行。任何指导或帮助将非常感谢。

1 个答案:

答案 0 :(得分:0)

试试这个:

use Illuminate\Http\JsonResponse;

并使用它来返回Json数据:

return new JsonResponse($variable);