Search code examples
laravelvalidationdingo-api

Laravel: Deny empty PUT requests in validation


Laravel 5.3's $api->resource() routes map PUT requests to the controller's update method.

I fail to trigger a validation error when an empty HTTP PUT request is made. My $this->validate() rules are all optional, since no field is required in an update. But I'd really like to let validation fail if the request is empty (count($request->all() == 0).

Is there a way to do that with the in-built validation rules?

A validation rule of '*' => 'min:1' does not work.


Solution

  • I did not find a working in-built rule, so I registered a custom rule:

        \Illuminate\Support\Facades\Validator::extendImplicit(
            'requestnotempty',
            function($attribute, $value, $parameters, $validator) {
                return count($validator->getData()) !== 0;
            }
        );
    

    Then I used it:

        $this->validate(
            $request,
            [
                '' => 'requestnotempty',
                //...
            ]
        );