【问题标题】:Laravel validation issueLaravel 验证问题
【发布时间】:2019-02-07 15:57:45
【问题描述】:

验证器规则时遇到问题

return [
            'features' => 'required|array',
            'features.*' => 'required|string',
            'link' => 'required|url',
            'image' => 'nullable|file|image|mimes:jpeg,png,gif,webp|max:2048',
        ];

返回一个错误,即字段是必需的,即使它们存在。 我不明白是什么导致了问题。我使用相同的验证进行存储,并且效果很好。

这是我的控制器的代码

public function update(UpdateSite $request, Site $site)
    {
        $validatedData = $request->validated();



        if ($validatedData['image']) {
            Storage::delete($site->path);

            $imagePath = $validatedData['image']->store('thumbnails');
            $interventedImage = Image::make(Storage::url($imagePath));
            $interventedImage->resize(500, null, function ($constraint) {
                $constraint->aspectRatio();
            });
            $interventedImage->save('storage/'.$imagePath);

            $site->update([
                'path' => $imagePath,
            ]);
        }

        $site->update([
            'site_link' => $validatedData['link'],
        ]);

        $site->features()->delete();

        if ($validatedData['features']) {
            foreach ($validatedData['features'] as $feature) {
                $site->features()->save(new SiteFeature(["feature" => $feature]));
            }
        }

        return $this->response->item($site, new SiteTransformer);
    }

更新 #1

我的路线 $api->put('sites/{id}', 'SiteController@update')->where(['id' => '\d+']);

【问题讨论】:

  • 用json请求测试看看是请求问题还是验证问题
  • @Hussein 刚刚创建了一个return var_dump($request->all()),它似乎是空的。我无法理解数据丢失的位置
  • 您确定该字段名称features[0] 吗?
  • @Hussein 是的。尽管如此,根据错误消息link也是空的
  • 能否包含验证和定义规则的完整代码?

标签: php laravel crud dingo-api


【解决方案1】:

我看到 api 方法是PUT,但您正在使用 form-data 的 Postman 来请求。尝试使用x-www-form-urlencoded请求你的api。

这是关于我的测试。对不起我的英语。

【讨论】:

    【解决方案2】:

    问题在于 PHP 在 PUTPATCH 请求中无法使用 multipart/form-data。很好奇这个问题仍然存在,因为互联网上有大约 2014 年的话题。

    解决方案

    在文档https://laravel.com/docs/5.6/routing#form-method-spoofing中有一个解决方案

    所以要更新一条记录,我只需要使用方法post 而不是put/patch 并发送一个输入字段_method = PUT

    刚刚自己尝试调用了put 路由。

    【讨论】:

      【解决方案3】:

      如果 features 是一个数组,那么第二行是正确的,但是如果您将 features 作为字符串传递,则应该删除第二行,此规则表示验证您有两个称为 features 的参数,其中一个是字符串,并且是必需的,其他也是数组和必需的

      'features' => 'required|array',
      'features.*' => 'required|string',
      

      【讨论】:

        猜你喜欢
        • 2015-06-28
        • 1970-01-01
        • 1970-01-01
        • 2015-06-22
        • 2016-07-01
        • 2018-04-01
        • 2014-05-10
        相关资源
        最近更新 更多