douzhun4124
2019-05-15 13:44
浏览 79
已采纳

使用表单请求时,Laravel的“给定数据无效”

So I have a Form Request that has validation rules and some messages.

This is my function in the controller (called via vue.axios)

public function store(TaskFormRequest $request, TaskService $service): JsonResponse
{
    $data = $request->validated();

    if (!$task = $service->create($data)) {
        return JsonResponse::create(['message' => __('Can\'t create Task')], 400);
    }

    return JsonResponse::create(
        [
            'task_id' => $task->id,
            'message' => __('Task was successfully added.'),
        ]
    );
}

It works OK, except that the moment store is called on (and $request is being considered TaskFormRequest instance) when the data is not validated it returns "The given data is invalid" JsonResponse in addition to the error messages from the form.

This would be fine, but the message itself is buried deep in Vendor and I can't apply any translations on it without it being a hassle.

This is my form request:

public function authorize(): bool
{
    return $this->user()->role === 'administrator';
}

public function rules(): array
{
    return [
        'subject' => 'required',
        'date' => 'nullable|date_format:Y-m-s',
        'user' => 'nullable|exists:users,id',
        'task_list_id' => 'required|exists:task_lists,id',
        'privacy' => 'array',
    ];
}

public function messages() {
    return [
        'subject.required' => __("Task name is empty")
    ];
}

I want to all together stop this response and just leave the errors from the form. Or at the least customize it.

EDIT: I think the problem is that the request is empty? If I enter a null default in the store function's arguments, I can check for empty $request and return a JsonResponse, but then it doesn't go through the normal validation process.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douna1895 2019-05-15 13:58
    已采纳

    The validator throws a Illuminate\Validation\ValidationException that you can intercept in the App\Exceptions\Handler->render() before it is sent to the parent Class in the vendor.

    if ($exception instanceof ValidationException) {
        //choose the structure you want. the Validation exception has many methods
        return response()->json(['status' => 'error', 'message' => $exception->getMessage()], 422);
    }
    

    edit: to intercept the error in the form request itself, declare the following method:

    public function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
    {
        throw (new \Illuminate\Validation\ValidationException($validator))
                    ->errorBag($this->errorBag)
                    ->redirectTo($this->getRedirectUrl());
    }
    
    点赞 打赏 评论
  • dongpao2871 2019-05-15 13:51

    What happen when you remove you messages() function ?

    (date_format:Y-m-s seems wrong, should'nt it be date_format:Y-m-d ? )

    点赞 打赏 评论

相关推荐 更多相似问题