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

使用表单请求时,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());
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)