elegantweb/sanitizer
Laravel package that cleans and normalizes user input before validation. Define sanitizer classes with rule sets to trim strings, cast types, strip tags, and transform request data, keeping controllers lean and application data consistent. Extensible with custom filters.
Install with Composer:
composer require elegantweb/sanitizer
Laravel auto-discovery should register the service provider. Publish the config if you need global rules or custom filter registration:
php artisan vendor:publish --provider="Elegant\Sanitizer\Laravel\SanitizerServiceProvider"
Look first at:
README.md for the supported filter list and exact Laravel integration API.src/Filters/ for the real behavior of trim, strip_tags, escape, cast, regex, remove, whitelist, numeric, etc.src/Laravel/ for the facade, middleware, and any SanitizesInput trait.config/sanitizer.php for global request filters and custom filter registration.A minimal first use case is normalizing a registration/profile payload before validation:
use Elegant\Sanitizer\Sanitizer;
$data = [
'name' => ' <b>Jane Doe</b> ',
'email' => ' [email protected] ',
];
$filters = [
'name' => 'strip_tags|trim',
'email' => 'trim|lowercase',
];
$clean = (new Sanitizer($data, $filters))->sanitize();
// ['name' => 'Jane Doe', 'email' => '[email protected]']
In Laravel, use it at the request boundary rather than in models or views. A FormRequest’s prepareForValidation() is the safest first integration point because validation rules then run against sanitized input:
use Elegant\Sanitizer\Laravel\Facades\Sanitizer;
protected function prepareForValidation(): void
{
$this->merge(
Sanitizer::make($this->all(), [
'name' => 'strip_tags|trim',
'email' => 'trim|lowercase',
])->sanitize()
);
}
If your installed version exposes a different facade/static API, resolve the sanitizer class from the container and call sanitize($data, $filters) or the equivalent constructor form shown above.
Use it as an input-normalization layer, not a validation layer. Sanitize before validation or inside prepareForValidation(), then let Laravel validation enforce presence, length, uniqueness, formats, and authorization. This keeps “cleaned data” and “valid data” separate in your mental model.
Centralize reusable field rules. Repeated arrays such as 'email' => 'trim|lowercase' belong in one place: a base FormRequest, a config-backed named sanitizer, or an app/Support/Sanitizers.php class. Day-to-day leverage comes from consistency: every email field is normalized the same way, every display name has tags stripped, every phone number goes through one rule.
Prefer per-request sanitization over global middleware. The package middleware is useful for broad normalization such as trimming all strings or stripping tags on a legacy /web group, but global middleware silently mutates every request, including APIs, webhooks, and rich-text admin payloads. Scope it:
Route::middleware('web')->group(function () {
// normal pages
});
Route::middleware(['web', 'sanitizer'])->group(function () {
// routes that tolerate global trimming/stripping
});
Exclude password, password confirmation, current-password, and rich-text fields from aggressive global rules.
Use pipeline order deliberately. Filters run left to right. strip_tags|trim removes tags first, then trims the whitespace left behind. trim|strip_tags can leave whitespace introduced by removed markup. Treat the filter string as a small transformation pipeline and test it with realistic payloads.
Use nested/dot notation when sanitizing arrays. The package supports applying filters to nested request data, typically with wildcards:
$filters = [
'profile.name' => 'trim|strip_tags',
'users.*.email' => 'trim|lowercase',
'users.*.nickname'=> 'trim|strip_tags',
];
This is valuable for $request->all() payloads, but verify wildcard behavior in your version and test empty/missing nested keys.
Add custom filters for domain normalization. When the built-in filters do not cover your domain—phone numbers to E.164, URL normalization, removal of control characters, transliteration—implement a small filter class and register it in config or the service provider:
use Elegant\Sanitizer\Filters\Filter;
class PhoneFilter implements Filter
{
public function apply($value, array $options = [])
{
return preg_replace('/[^\d+]/', '', (string) $value);
}
}
Keep custom filters pure, deterministic, and free of database calls. They should be cheap transformations, not workflows.
Use cast carefully, and validate after casting. cast:integer, cast:boolean, cast:array, and similar filters change types before validation sees them. That is useful for API normalization, but it can hide malformed input: "12abc" may become 12, and boolean casting can surprise you with strings like "false". Validate the original or the cast result explicitly.
Pair with FormRequest tests. The highest-leverage workflow is a small test suite that asserts the exact sanitized output for the filter strings you use:
$sanitized = (new Sanitizer($payload, $filters))->sanitize();
$this->assertSame('Jane Doe', $sanitized['name']);
$this->assertSame('[email protected]', $sanitized['email']);
Test nulls, empty strings, arrays, unicode whitespace, HTML entities, numeric strings, and nested payloads. This is more valuable than reading the filter source once, because filter behavior and package versions can change.
strip_tags does not make content safe for every output context; Blade {{ }} escaping, parameterized SQL, and context-aware output encoding are still required. Do not treat escape as a database security measure.{{ $value }}, users may see &lt;. Prefer storing normalized text and escaping at output time; apply escape only when you intentionally need an HTML-safe string.trim may not remove unicode whitespace. PHP’s default trim character list does not cover non-breaking spaces or some multibyte whitespace. For user input, consider a custom regex filter or an explicit character list if this matters.strip_tags is not an HTML purifier. It removes markup, including attributes and potentially useful rich-text structure. If users submit rich text, use a dedicated HTML sanitizer such as HTMLPurifier, not this package’s strip_tags, and whitelist tags/attributes explicitly.$request->all() includes UploadedFile instances. Running string filters over uploaded files can break them or throw type errors. Sanitize $request->except(array_keys($request->allFiles())) or use $request->input() with explicit keys.null, arrays, or objects. Guard with filled()/is_string() in custom filters, and test the exact edge cases your form allows.lowercase|trim and trim|lowercase often agree, but strip_tags|trim versus trim|strip_tags can differ visibly.config/sanitizer.php, run php artisan config:clear locally and rebuild config:cache in production. Otherwise you will debug stale behavior.TrimStrings and ConvertEmptyStringsToNull already normalize input. Decide whether the sanitizer middleware runs before or after them, and avoid contradictory rules such as one layer turning empty strings into null while another expects strings.Elegant\Sanitizer, not the vendor name in the package string. For Lumen or older Laravel versions, register the provider/facade manually. Pin the version and review the changelog; this is a small package, so avoid assuming long-term API stability.TrimStrings, ConvertEmptyStringsToNull, validation rules, and prepareForValidation() cover most cases. Reach for this package when you want a declarative filter pipeline and consistent field-level normalization across many forms; do not add it as a security layer or a replacement for validation.How can I help you explore Laravel packages today?