Sanitize request input before passing to validation.
composer require adamthehutt/laravel-sanitized-requests
Create a Request class and use the SanitizesInput
trait. Then implement
the sanitize(Sanitizer $sanitizer)
method to clean up user input before it is
validated.
use AdamTheHutt\SanitizedRequests\SanitizesInput;
use AdamTheHutt\SanitizedRequests\Sanitizer;
use Illuminate\Foundation\Http\FormRequest;
class StoreItem extends FormRequest
{
use SanitizesInput;
public function sanitize(Sanitizer $sanitizer): void
{
$sanitizer->castToInt("user_id")
->castToBoolean("for_sale")
->castToFloat("price")
->forgetIfEmpty("item_description")
->trimWhitespace("nested.*.wildcard.param");
}
}
The following sanitize methods are currently supported:
- castToBool($key) - Casts the string input value to a boolean
- castToInt($key) - Casts the string input value to an integer
- castToFloat($key) - Casts the string input value to a float
- castToString($key) - Casts the input value to a string
- forgetIfEmpty($key) - Removes from input both empty strings and arrays with only empty values
- map($key, $callable) - Applies an arbitrary callback to the input value(s)
- trimWhitespace($key) - Trims whitespace from a string input value