Laravel验证问题

时间:2018-09-02 08:56:56

标签: php laravel crud dingo-api

验证器规则时出现问题

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

给我一​​个错误,提示即使存在字段也必须填写。 enter image description here 我不明白是什么原因引起的。我使用相同的验证进行存储,并且效果很好。

这是我控制器的代码

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+']);

3 个答案:

答案 0 :(得分:0)

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

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

enter image description here

enter image description here

答案 1 :(得分:0)

问题出在PHP中,该PHP无法与multipart/form-dataPUT请求中的PATCH一起使用。很好奇这个问题仍然存在,因为大约有2014年的互联网主题。

解决方案

文档https://laravel.com/docs/5.6/routing#form-method-spoofing

中有一个解决方案

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

只需尝试调用put路由即可。

答案 2 :(得分:-1)

如果features是一个数组,那么第二行是正确的,但是如果您将features作为字符串传递,则应该删除第二行,此规则说,验证您是否有两个称为features的参数,其中一个是string,是必需的,另一个也是array并要求

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