phplaravelvalidationrule

how to fail Laravel validate if extra param pass to it?


I'm using Laravel validation for validate user request. it's work for me but I need to validation failed if user send any parameter more than that mentioned in rules. for example if the rule is like this:

['id'=>'required|integer']

if user send anything extra like

'name'=>'foo'

the validation should failed and the error message is something like:

the name param is not allowed.

Solution

  • you can create a base class for requests and get the keys of all rules in the request class, then get the keys of user requests. if there is any extra parameter you can easily generate an error for unsupported data passed. note that some parameters for laravel should be exclude from this rule like pagination parameters or _method . this list is in the code.

     private function checkExtraInput()
    {
        if ($this->validator) {
            $rules = $this->validator->getRules();
        } else {
            $rules = $this->rules();
        }
        $expectedKeys = array_keys($rules);
        // if the rules contain nested parametes we need to just check the first part.
        foreach ($expectedKeys as &$key) {
            $key = explode('.', $key)[0];
        }
        // allowed parameters for laravel
        foreach (['_method', 'page', 'limit', 'search', 'include', 'filter'] as $allow) {
            if (array_search($allow, $expectedKeys) === false) {
                $expectedKeys[] = $allow;
            }
        }
        if ($this->validator) {
            $data = $this->validator->getData();
        } else {
            $data = $this->all();
        }
        $gottonData = array_keys($data);
        // get the different of user parameters
        $dif = array_diff($gottonData, $expectedKeys);
        if ($dif) {
            abort(423, 'the extra parameter not allowed:'.implode(',', $dif));
        }
    }
    
    public function validated($key = null, $default = null)
    {
        $this->checkExtraInput();
    
        return parent::validated();
    }