我正在使用 Laravel FormRequest 来避免控制器内部出现混乱的验证请求。为此,我指的是这篇文章 https://medium.com/@kamerk22/the-smart-way-to-handle-request-validation-in-laravel-5e8886279271
问题是每次我调用 store 方法时,都会抛出以下错误
{message: "The given data was invalid.",…}
message: "The given data was invalid."
errors: {affinity_id: ["The affinity id field is required."],…}
affinity_id: ["The affinity id field is required."]
partner_name: ["The partner name field is required."]
tier_id: ["The tier id field is required."]
country_id: ["The country id field is required."]
partner_user_name: ["The partner user name field is required."]
partner_user_email: ["The partner user email field is required."]
partner_user_mobile: ["The partner user mobile field is required."]
contacted_for_id: ["The contacted for id field is required."]
issue_type_id: ["The issue type id field is required."]
comm_mode_id: ["The comm mode id field is required."]
opened_by_id: ["The opened by id field is required."]
assigned_to_id: ["The assigned to id field is required."]
team_id: ["The team id field is required."]
priority_id: ["The priority id field is required."]
tat_id: ["The tat id field is required."]
resolve_date: ["The resolve date field is required."]
status_id: ["The status id field is required."]
description: ["The description field is required."]
我正在使用 ajax 调用 store 方法
这是我的代码
控制器
namespace App\Http\Controllers\tracker;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Http\Requests\TicketStoreRequest;
public function store(TicketStoreRequest $request)
{
$validators = $request->validated();
if ($validators->fails()) {
$data['result'] = false;
$data['messages'] = $validators->errors()->first();
return json_encode($data);
}
}
表单请求类
public function authorize()
{
return true;
}
public function rules()
{
return [
'affinity_id' => 'required',
'partner_name' => 'required',
'tier_id' => 'required',
'country_id' => 'required',
'partner_user_name' => 'required',
'partner_user_email' => 'required',
'partner_user_mobile' => 'required',
'contacted_for_id' => 'required',
'issue_type_id' => 'required',
'comm_mode_id' => 'required',
'opened_by_id' => 'required',
'assigned_to_id' => 'required',
'team_id' => 'required',
'priority_id' => 'required',
'open_date' => 'required',
'tat_id' => 'required',
'resolve_date' => 'required',
'status_id' => 'required',
'description' => 'required'
];
}
此行为仅在不满足规则时发生。如果所有字段均已成功验证,则TicketStoreRequest
类不会引发错误。