Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Sanitizer Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

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.
  • The published 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.

Implementation Patterns

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.

Gotchas and Tips

  • Sanitization is not escaping and not validation. 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.
  • Avoid double escaping. If you store escaped HTML and later render it with Blade {{ $value }}, users may see &amp;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.
  • Watch out for file uploads. $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.
  • Nulls, arrays, and non-strings can bite. Filters that assume strings may coerce, throw, or behave unexpectedly on null, arrays, or objects. Guard with filled()/is_string() in custom filters, and test the exact edge cases your form allows.
  • Do not trim or lowercase passwords. Global middleware that trims all input will alter passwords and can break authentication. Exclude password fields and any field where whitespace is semantically meaningful.
  • Filter order changes results. Document and test the order. lowercase|trim and trim|lowercase often agree, but strip_tags|trim versus trim|strip_tags can differ visibly.
  • Custom filters must be registered before use. Unknown filter names may throw or silently pass data through depending on version. Add a test that exercises each custom filter name so a config mistake fails loudly.
  • Clear config cache after changing sanitizer rules. If rules live in config/sanitizer.php, run php artisan config:clear locally and rebuild config:cache in production. Otherwise you will debug stale behavior.
  • Middleware ordering matters. Laravel’s 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.
  • Scope global middleware away from APIs. Sanitizing every JSON request can silently change API contracts. Prefer per-controller or per-FormRequest rules for APIs, and reserve middleware for legacy HTML form flows.
  • Check the package namespace and Laravel version constraints. The namespace is 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.
  • Debug by dumping before and after. When a validation rule fails unexpectedly, log or dump the sanitized payload immediately before validation. Most surprises come from filter order, type casting, or global middleware touching a field you forgot about.
  • Know when not to use it. For simple needs, Laravel’s 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.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
mrnewport/laravel-plaid
mrnewport/laravel-repo
mrnewport/laravel-docsign
mrnewport/laravel-stow
mrnewport/laravel-flow
mrnewport/laravel-priceable
mrnewport/laravel-nestedterms
fredmeng/laravel-apidoc-generator
itstructure/laravel-multilingual-tools
pdustdar/elasticsearch
markupai/php-sdk
rlacerda83/lumem-microservice-shipment
uni-method/symfony-lib
tacticmedia/scim-server-bundle
neika-ai/symfony-bundle
mattleads/agent-publishing-bundle
glavweb/framework-bundle
glavweb/extra-bundle
glavweb/api-bundle
glavweb/admin-bundle