Is there a request/validation rule that would throw an error in case of unexpected input?

Something like Request::only() that throws an error if there is any extra/unexpected field in the request?

E.g.:

$request->strictly(['username', 'password']);

that would throw an error if POST request contains fields ‘username’, ‘password’, and ‘foo’?

In case there isn’t, what would be the best way to perform such a verification manually?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can create your own strictly method in the request class using Macro

AppServiceProvider.php and inside boot method add this method

use IlluminateHttpRequest;
use IlluminateValidationValidationException;

public function boot()
{
     Request::macro('strictly', function(array $paramaters) {
       $array = array_diff(request()->keys(), $paramaters);
        if (count($array) > 0) {
            throw ValidationException::withMessages(
                collect($array)->map(function ($row) {
                    return [$row => 'not needed'];
                })->collapse()->all()
            );
        }
      });
}

Now You can use this method inside the controller or request class
request()->strictly(['username', 'password']);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x