gpt4 book ai didi

php - Laravel 自定义验证器返回页面而不是 json

转载 作者:行者123 更新时间:2023-12-05 04:31:03 27 4
gpt4 key购买 nike

我做了一个 Controller 来存储任务,它看起来像:

    public function store(StoreTaskRequest $request)
{
$validated = $request->validated();

return response()->json($request);
}

对于请求验证,我制作了一个自定义验证器,看起来像

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreTaskRequest 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 [
'project_id' => 'required',
'project_name' => 'required',
'task_id' => 'required',
'task_name' => 'required',
'startDate' => 'required',
'endDate' => 'required',
];
}

public function messages()
{
return [
'project_id.required' => 'required!',
'project_name.required' => 'required!',
'task_id.required' => 'required!',
'task_name.required' => 'required!',
'startDate.required' => 'required!',
'endDate.required' => 'required!',
];
}
}

当我使用不正确的数据向该 Controller 发出发布请求时,它返回一个 html 页面,但是当我使用正确的数据发布它时,它以 json 格式返回请求

顺便说一下,我通过以下方式发出发帖请求:reqbin.com

Post request headers: 
X-Csrf-Token: ....
Content-Type: application/json

Post Params:
{
"project_name": "Wiza",
"task_id": 1,
"task_name": "test 1",
"startDate": {
"week": 1,
"start" : 11,
"year": 2022
},
"endDate": {
"week": 1,
"start" : 11,
"year": 2022
}
}

有谁知道为什么它返回的是 html 页面而不是验证错误?

编辑:

api.php 是空的网页.php

Route::post('api/v1/tasks/', [TaskController::class, 'store']);

//Also tried
Route::resource('api/v1/tasks/', TaskController::class);

最佳答案

在您的自定义验证器中添加此代码。

/**
* Get the error messages for the defined validation rules.*
* @return array
*/
protected function failedValidation(ValidationValidator $validator)
{
throw new HttpResponseException(response()->json([
'message' => implode('', collect($validator->errors())->first()),
'status' => true
], 422));
}

关于php - Laravel 自定义验证器返回页面而不是 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71927088/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com