PHPackages                             kalfheim/sanitizer - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Search &amp; Filtering](/categories/search)
4. /
5. kalfheim/sanitizer

ActiveLibrary[Search &amp; Filtering](/categories/search)

kalfheim/sanitizer
==================

Data sanitizer for PHP with built-in Laravel support.

v1.0.1(10y ago)1423.7k4[2 issues](https://github.com/kalfheim/sanitizer/issues)[1 PRs](https://github.com/kalfheim/sanitizer/pulls)MITPHPPHP &gt;=5.5.9

Since Mar 23Pushed 9y ago4 watchersCompare

[ Source](https://github.com/kalfheim/sanitizer)[ Packagist](https://packagist.org/packages/kalfheim/sanitizer)[ Docs](http://github.com/kalfheim/sanitizer)[ RSS](/packages/kalfheim-sanitizer/feed)WikiDiscussions master Synced 2mo ago

READMEChangelog (2)Dependencies (3)Versions (3)Used By (0)

sanitizer
=========

[](#sanitizer)

[![Build Status](https://camo.githubusercontent.com/58c45c8a4af6a22e7dedb8aef659281baf84d88e882d1e946ab3710b2e86fa94/68747470733a2f2f7472617669732d63692e6f72672f6b616c666865696d2f73616e6974697a65722e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/kalfheim/sanitizer)[![StyleCI](https://camo.githubusercontent.com/e6e42f95b2b14013c35a08c027b572146b4fafaf404ef402012300f0477f414c/68747470733a2f2f7374796c6563692e696f2f7265706f732f35343537393830372f736869656c64)](https://styleci.io/repos/54579807)[![Code Coverage](https://camo.githubusercontent.com/9a247667d936d936d21743c3e519cab2ba755c3f949c75fd11fce6cca8e0cb91/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6b616c666865696d2f73616e6974697a65722f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/kalfheim/sanitizer/?branch=master)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/8863645886cf75f25049033205432834c4d388217366849825a0e84ff2d33de5/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6b616c666865696d2f73616e6974697a65722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/kalfheim/sanitizer/?branch=master)[![Latest Stable Version](https://camo.githubusercontent.com/77a894d770d06ee4ed665ab2a82f1c0256526dca67f8a67d9792dda4f314c2db/68747470733a2f2f706f7365722e707567782e6f72672f6b616c666865696d2f73616e6974697a65722f762f737461626c65)](https://packagist.org/packages/kalfheim/sanitizer)[![Latest Unstable Version](https://camo.githubusercontent.com/6a61b8c25d3c0dd559390eefb543d5fa3bdbe357a0357961bc55c4a246c978e5/68747470733a2f2f706f7365722e707567782e6f72672f6b616c666865696d2f73616e6974697a65722f762f756e737461626c65)](https://packagist.org/packages/kalfheim/sanitizer)[![License](https://camo.githubusercontent.com/a9ade40c984660092bfb10718c25b0f80e2dae76d2a8fe9d6d7c4d5fc40cb50a/68747470733a2f2f706f7365722e707567782e6f72672f6b616c666865696d2f73616e6974697a65722f6c6963656e7365)](https://packagist.org/packages/kalfheim/sanitizer)

> Data sanitizer for PHP with built-in Laravel support.

Installation
------------

[](#installation)

```
composer require kalfheim/sanitizer

```

Usage
-----

[](#usage)

```
use Alfheim\Sanitizer\Sanitizer;

// Create a new sanitizer instance by passing an array of rules to the `Sanitizer::make` method...
$sanitizer = Sanitizer::make([
    'email' => 'trim',
]);

// Simulate some user input...
$input = [
    'email' => 'name@example.com ', // Notice the space.
];

// Now we will sanitize some data by passing an array to the `sanitize` method...
var_dump($sanitizer->sanitize($input)); // ['email' => 'name@example.com']

// It is also possible to pass the data by reference using the `sanitizeByRef` method...
$sanitizer->sanitizeByRef($input);
var_dump($input); // ['email' => 'name@example.com']
```

### Examples

[](#examples)

```
// Wildcard example...

$input = [
    'name'  => 'Ola nordmann',
    'email' => 'Name@example.com ',
];

$sanitizer = Sanitizer::make([
    '*'     => 'trim',          // `*` is a wildcard which will apply to all fields.
    'name'  => 'ucwords',       // Uppercase first char of each word in the name field.
    'email' => 'mb_strtolower', // Lowercase each letter in the email field.
]);

var_dump($sanitizer->sanitize($input));
// ['name' => 'Ola Nordmann', 'email' => 'name@example.com']
```

```
// Multiple rules and arguments...

$sanitizer = Sanitizer::make([
    'name'  => 'trim|ucwords', // Trim, then uppercase first char of each word.
    'email' => 'preg_replace:/\+\w+/::{{ VALUE }}',
]);

// The `email` rule might be a handful, but it is really quite simple.
// The rule translates to `$sanitizedValue = preg_replace('/\+\w+/', '', $value)`.
// It will sanitize an email like `name+foo@example.com` to `name@example.com`.

// The `{{ VALUE }}` string is a magic constant that the sanitizer will replace
// with the value currently being sanitized.

// By default, the value will be implicitly bound to the first argument in the list,
// however, you can place it where ever you need to satisfy the function being called.

$sanitizer = Sanitizer::make([
    'foo' => 'mb_substr:0:1',
    'bar' => 'mb_substr:{{ VALUE }}:0:1',
]);

// In the example above, both rules will achieve the same end result.
```

Registrars
----------

[](#registrars)

A registrar allows you to bind custom sanitizer functions to the sanitizer.

```
use Alfheim\Sanitizer\Sanitizer;
use Alfheim\Sanitizer\Registrar\BaseRegistrar;

// Create a new registrar instance...
$registrar = new BaseRegistrar;

// Add custom sanitation rules to the registrar...
$registrar->register('palindromify', function (string $value) {
    return sprintf('%s%s', $value, strrev($value));
});

// Create a new sanitizer and bind the registrar...
$sanitizer = Sanitizer::make([
    'number' => 'palindromify',
])->setRegistrar($registrar);

$input = $sanitizer->sanitize([
    'number' => '123',
]);

var_dump($input); // ['number' => '123321']
```

Laravel Support
---------------

[](#laravel-support)

Register the service provider in your `config/app.php` as per usual...

```
Alfheim\Sanitizer\SanitizerServiceProvider::class,

```

### Extending the FormRequest

[](#extending-the-formrequest)

**This is where the package shines.**By extending the `Alfheim\Sanitizer\Laravel\FormRequest` on your base `App\Http\Requests\Request` class (instead of the default `Illuminate\Foundation\Http\FormRequest`), you'll be able to define sanitation rules in a `sanitize` method on the given form request, similar to how you define validation rules in the `rules` method.

Let me show you in code...

```
// app/Http/Requests/Request.php

namespace App\Http\Requests;

use Alfheim\Sanitizer\Laravel\FormRequest;
// Instead of `Illuminate\Foundation\Http\FormRequest`

abstract class Request extends FormRequest
{
    //
}
```

That's it! Now it's trivial to define sanitation rules on your form requests...

```
// app/Http/Requests/FooRequest.php

namespace App\Http\Requests;

class FooRequest extends Request
{
    // Sanitation rules...
    public function sanitize()
    {
        return [
            'name'  => 'trim|ucwords',
            'email' => 'trim|mb_strtolower',
        ];
    }

    // And of course, validation is defined as per usual...
    public function rules()
    {
        return [
            'name'  => 'required',
            'email' => 'required|email',
        ];
    }
}
```

For completeness, I'll show you the controller...

```
namespace App\Http\Controllers;

use App\Http\Requests\FooRequest;

class FooController extends Controller
{
    public function create(FooRequest $request)
    {
        // At this point, the $request will be both sanitized and validated.
        // You may go ahead and access the input as usual:

        $request->all();
        $request->input('name');
        $request->only(['name', 'email']);
        // etc...
    }
}
```

### Helper Trait

[](#helper-trait)

#### `Alfheim\Sanitizer\Laravel\SanitizesRequests`

[](#alfheimsanitizerlaravelsanitizesrequests)

This trait adds a `sanitize` method on the class. May be useful if you want to sanitize user input in a controller without setting up a custom request class (however, it *can* be used from anywhere.)

```
public function sanitize(Illuminate\Http\Request $request, array $ruleset): array
```

Example usage...

```
namespace App\Http\Controllers\FooController;

use Illuminate\Http\Request;
use Alfheim\Sanitizer\Laravel\SanitizesRequests;

class FooController extends Controller
{
    use SanitizesRequests;

    public function store(Request $request)
    {
        $input = $this->sanitize($request, [
            'name'  => 'trim|ucwords',
            'email' => 'trim|mb_strtolower',
        ]);

        // $input now contains the sanitized request input.
    }
}
```

### Registering custom sanitizer functions with Laravel

[](#registering-custom-sanitizer-functions-with-laravel)

The service provider will register a shared `Alfheim\Sanitizer\Registrar\RegsitrarInterface` instance with the IoC container, which will then be set on subsequent `Alfheim\Sanitizer\Sanitizer` instances. This means you can easily register custom sanitizer functions...

```
use Alfheim\Sanitizer\Registrar\RegistrarInterface;

// Standalone...
app(RegistrarInterface::class)->register('yell', $callable);

// In a method resolved by the container, perhaps a service provider...
public function registerSanitizers(RegistrarInterface $registrar)
{
    $registrar->register('yell', function (string $value) {
        return mb_strtoupper($value);
    });
}

// You may also resolve an object from the IoC container using `class@method` notation...
app(RegistrarInterface::class)->register('foo', 'some.service@sanitizerMethod');
```

License
-------

[](#license)

[MIT](LICENSE) © [Kristoffer Alfheim](http://github.com/kalfheim)

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance17

Infrequent updates — may be unmaintained

Popularity32

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

2

Last Release

3707d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/4445087?v=4)[Kristoffer Alfheim](/maintainers/kalfheim)[@kalfheim](https://github.com/kalfheim)

---

Tags

laravelsanitizerfilterfilteringsanitation

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/kalfheim-sanitizer/health.svg)

```
[![Health](https://phpackages.com/badges/kalfheim-sanitizer/health.svg)](https://phpackages.com/packages/kalfheim-sanitizer)
```

###  Alternatives

[htmlawed/htmlawed

Official htmLawed PHP library for HTML filtering

401.1M9](/packages/htmlawed-htmlawed)[pos-lifestyle/laravel-nova-date-range-filter

A Laravel Nova date range filter.

16179.1k](/packages/pos-lifestyle-laravel-nova-date-range-filter)[tapp/filament-value-range-filter

Filament country code field.

2362.2k](/packages/tapp-filament-value-range-filter)[webbingbrasil/filament-datefilter

Date filter component for filament tables.

1479.4k](/packages/webbingbrasil-filament-datefilter)[ambengers/query-filter

Laravel package for filtering resources with request query string

3513.5k](/packages/ambengers-query-filter)[mobileka/scope-applicator

Scope Applicator is a PHP trait that makes data filtering and sorting easy.

251.2k2](/packages/mobileka-scope-applicator)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
