使用请求 class 时如何将验证响应设为 json

How to make validation response as json when using request class

我有这些请求文件来注册一个新客户,我想在验证失败时得到响应json,我该怎么做?

这是请求class

<?php

namespace App\Http\Requests\Validations;

use App\Http\Requests\Request;


class RegisterCustomerRequest extends Request
{

public function authorize()
{
    return true;
}

public function rules()
{
    return [
        'name' => 'required|min:3|max:255',
        'email' => 'required|email|max:255|unique:customers',
        'password' => 'required|string|min:6|confirmed',
        'agree' => 'required',
    ];
}
}

以及注册函数:

public function register(RegisterCustomerRequest $request)
{
    $customer = Customer::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => $request->password,
        'accepts_marketing' => $request->subscribe,
        'verification_token' => Str::random(40),
        'active' => 0,
    ]);

    // Sent email address verification notich to customer
    $customer->notify(new EmailVerificationNotification($customer));

    $customer->generateToken();

    event(new Registered($customer));

    return new CustomerResource($customer);
}

在您的 RegisterCustomerRequest 中,您可以覆盖默认方法 failedValidation,如下所示

 protected function failedValidation(Validator $validator)
    {

        if ($this->ajax()){

            throw new HttpResponseException($this->respondWithError(419,'VALIDATION_ERROR',$validator->errors()));
        } else{
            throw (new ValidationException($validator))
                ->errorBag($this->errorBag)
                ->redirectTo($this->getRedirectUrl());
        }


    }

您也可以在 $this->ajax() 中写下您自己的回复,如下所示

if ($this->ajax()){
     return response()->json($validator->errors(),419);
}