Skip to content

Instantly share code, notes, and snippets.

@gcphost
Last active April 20, 2018 15:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gcphost/cd2c61acfb97c8e613aa7289241fed47 to your computer and use it in GitHub Desktop.
Save gcphost/cd2c61acfb97c8e613aa7289241fed47 to your computer and use it in GitHub Desktop.
Sanitize input with Laravel 5 Validator https://github.com/Askedio/laravel-validator-filter

Install

composer require daylerees/sanitizer
composer require mews/purifier
<?php
Route::get('/', function () {
app('sanitizer')->register('reverse', function ($field) {
return strrev($field);
});
/** custom filter */
$validator = app('validator')->make(request()->all(), [
'title' => 'filter:reverse|required|max:255',
'body' => 'required',
]);
/** xss filter */
$validator = app('validator')->make(request()->all(), [
'title' => 'filter:clean|required|max:255',
'body' => 'required',
]);
return $validator->fails() ? $validator->errors() : 'pass';
});
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
app('validator')->extend('filter', function ($attribute, $value, $parameters, $validator) {
$data = [$attribute => $value];
app('sanitizer')->sanitize([$attribute => $parameters], $data);
$replace = array_merge(array_dot($validator->getData()), [$attribute => $data[$attribute]]);
request()->replace(array_merge(request()->all(), $array));
$validator->setData($replace);
return true;
});
}
public function register()
{
app()->register('Rees\Sanitizer\SanitizerServiceProvider');
app()->register('Mews\Purifier\PurifierServiceProvider');
}
}
@lukasoppermann
Copy link

A problem I encountered is that it does not work with multidimensional arrays (using dot matrix e.g. data.value). The problem is that the $attribute will be data.value but the data returned from $validator->getData() is a normal array, so the array_merge leads to a duplication with the array and the dot array being added and the actual replacement not being correctly applied.

You would beed to convert the $validator->getData() into a dot matrix before merging.

@gcphost
Copy link
Author

gcphost commented May 6, 2016

Thank you, I have updated the example.

@gcphost
Copy link
Author

gcphost commented Feb 14, 2018

Request vars were being removed if not part of the validator.

I've changed

 request()->replace($array);

to

request()->replace(array_merge(request()->all(), $array));

Now original request vars will remain.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment