Sanitize data using a number of mutation methods.



Travis Status Github Release Packagist License Packagist Downloads Github Issues Tips

Sanitizer Package

Sanitizers can be used to standardize data to ease validation, or provide data consistency.


The Sanitizer package can be used stand-alone or with the Laravel Framework.


First include the sanitizer package.

"developerdynamo/sanitizer": "dev-master"

Now simply use the Sanitizer class.

use DeveloperDynamo\Sanitizer\Sanitizer;

With Laravel

Include the Service Provider class within the app/config/app.php file.

'providers' => array(

Now simply add the facade alias.

'aliases' => array(
    'Sanitizer' => DeveloperDynamo\Sanitizer\Facade::class,

Basic Usage

First construct a rules array.

$rules = [
    'name'      => 'trim',
    'email'     => 'trim|strtolower'

Rules can contain either callable functions, or the name of a sanitizer binding (more later). You can use either a pipe | or an array to specify multiple sanitization rules.

The sanitizer can be executed in the following fashion.

$sanitizer = new Sanitizer;
$sanitizer->sanitize($rules, $data);

Here's a full example.

// Construct rules array.
$rules = [
    'name'      => 'trim',
    'email'     => 'trim|strtolower'

// Data array to be sanitized.
$data = [
    'name' => ' Dayle ',
    'email' => ''

// Construct a new sanitizer.
$sanitizer = new Sanitizer;

// Execute the sanitizer.
$sanitizer->sanitize($rules, $data);

Here's the content of $data after execution.

    'name' => 'Dayle',
    'email' => ''

Using the Laravel facade, the syntax can be made a little cleaner.

Sanitizer::sanitize($rules, $data);

Custom Sanitization Rules

Sanitizers can be added multiple ways.

Using a Closure.

Sanitizer::register('reverse', function ($field) {
    return strrev($field);

Using a Callback.

Sanitizer::register('reverse', [new ClassHere, 'method']);

Using a class/method pair.

Sanitizer::register('reverse', 'Namespace\Class\Here@method');

The class will be resolved through an instance of the Illuminate IoC container, if no method is provided then sanitize() is assumed.

Global rule

IT allows a user to set global sanitizer rules to be applied to every item in the dataset. Simply set an item in the rules array that uses "*" as the key, for example:

$rules = [
    '*' => 'trim|strtolower',
    'last_name' => 'strrev',

Global rules will then be processed prior to the field-specific rules.

Available rules

  • trim: remove space before and ater a string
  • lowercase: convert a string in lower case format
  • uppercase: convert a string in uppercase format
  • ucfirst: Convert in uppercase the first character of a given string
  • html: encode html tags in UTF-8 entities