phplaravelcruddingo-api

Laravel validation issue


I'm experiencing an issue when validator rules

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

Return me an error that fields are required even if they are present. enter image description here I can't understand what causes the problem. I use identical validation for storing and it works perfectly.

Here is my controller's code

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);
    }

Update #1

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


Solution

  • The problem lies in PHP which cannot work with multipart/form-data in PUT, PATCH request. Very curious that this problem is still present since there are in the Internet topics from about 2014.

    Soulution

    There is a solution in docs https://laravel.com/docs/5.6/routing#form-method-spoofing

    So to update a record all I need is to use method post instead of put/patch and send an input field _method = PUT.

    Just tried myself the put route was invoked.