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 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教