下一个是我的FormRequest:
<?php
namespace AppHttpRequests;
use IlluminateFoundationHttpFormRequest;
class StoreFruitRequest 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()
{
return [
'name' => 'required|string|min:3',
'carbohydrates' => 'required|numeric|gte:0',
'protein' => 'required|numeric|gte:0',
'fat' => 'required|numeric|gte:0',
'calories' => 'required|integer|numeric|gte:0',
'sugar' => 'required|numeric|gte:0',
];
}
/**
* Error Messages
*
* @return array
*/
public function messages() :array
{
return [
'carbohydrates.gte' => 'Nutrients cannot be negative',
'protein.gte' => 'Nutrients cannot be negative',
'fat.gte' => 'Nutrients cannot be negative',
'calories.gte' => 'Nutrients cannot be negative',
'sugar.gte' => 'Nutrients cannot be negative',
];
}
}
验证规则工作正常,但是当我使用错误的值(这是一个负值)发出请求时,验证不会将这些消息返回给控制器。因此,我的API返回主刀片页面作为一个错误。
什么是不正确的在我的代码?或者,我需要在任何地方进行调整吗?
控制器(作为@NickSdot的答案):
/**
* Store a newly created resource in storage.
*
* @param StoreFruitRequest $request
* @return JsonResponse
*/
public function store(StoreFruitRequest $request)
{
return response()->json(Fruit::create($request->all()) ?? "Cannot create fruit $request->name");
}
你可以在middleware文件夹中添加一个名为ForceJsonResponse.php的中间件,然后将它添加到Kernel.php的$middleware变量中。
ForceJsonResponse.php
use Closure;
use IlluminateHttpRequest;
class ForceJsonResponse
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure(IlluminateHttpRequest): (IlluminateHttpResponse|IlluminateHttpRedirectResponse) $next
* @return IlluminateHttpResponse|IlluminateHttpRedirectResponse
*/
public function handle(Request $request, Closure $next)
{
$request->headers->set('Accept', 'application/json');
return $next($request);
}
}
Kernel.php
protected $middleware = [
//your other classes
AppHttpMiddlewareForceJsonResponse::class,
];