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'); | |
} | |
} |
Thank you, I have updated the example.
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.
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 bedata.value
but the data returned from$validator->getData()
is a normal array, so thearray_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.