我创建了一个自定义验证类,位于app\Http\Requests
:
<?php
namespace App\Http\Requests;
use App\Http\Requests\BaseFormRequest;
class RegisterUserRequest extends BaseFormRequest
{
protected static $NEEDS_AUTHORIZATION = false;
protected static $FORM_RULES = [
'first_name' => 'required|string|max:80',
'last_name' => 'required|string|max:80',
'email' => 'required|unique:users|email',
'password' => 'required|string|min:6|confirmed',
'terms_conditions' => 'accepted'
];
}
BaseFormRequest
并在同一目录中扩展:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Exceptions\HttpResponseException;
//use Illuminate\Http\Request;
abstract class BaseFormRequest extends FormRequest
{
protected static $NEEDS_AUTHORIZATION = true;
protected static $FORM_RULES = [];
protected static $ERROR_MESSAGES = [];
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize() : bool
{
return !static::$NEEDS_AUTHORIZATION;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules() : array
{
return static::$FORM_RULES;
}
/**
* Get the error messages for the defined validation rules.
*
* @return array
*/
public function messages()
{
return static::$ERROR_MESSAGES;
}
/**
* @overrride
* Handle a failed validation attempt.
*
* @param \Illuminate\Contracts\Validation\Validator $validator
* @return void
*
* @throws \Illuminate\Validation\ValidationException
*/
protected function failedValidation(Validator $validator) : void
{
//throw (new ValidationException(response()->json($validator->errors(), 422)));
throw new HttpResponseException(response()->json($validator->errors(), 422));
}
}
现在,当尝试在我的控制器中使用它时:
<?php
namespace App\Http\Controllers\API;
use App\Services\UserService;
use Illuminate\Http\JsonResponse as JsonResponse;
//use Iluminate\Http\Request;
use App\Http\Requests\RegisterUserRequest;
class UserController extends Controller
{
private $user;
public function __construct(UserService $user)
{
$this->user = $user;
}
public function store(RegisterUserRequest $request) : JsonResponse
{
$registered_user = $this->user->register($request->validated());
return response()->json(['status' => 201, 'user_id' => $registered_user->id]);
}
}
我收到以下错误:
ReflectionException 类 App\Http\Requests\RegisterUserRequest 不存在
有趣的是,如果我删除了被覆盖的方法failedValidation
,错误就消失了,尽管它会将我重定向到我试图避免的主页。我想总是返回一个 json 响应。
有什么建议么?谢谢