Home > Back-end >  Is there a request/validation rule that would throw an error in case of unexpected input?
Is there a request/validation rule that would throw an error in case of unexpected input?

Time:09-16

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?

CodePudding user response:

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

AppServiceProvider.php and inside boot method add this method

use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

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