Installation:
composer require webpatser/laravel-sanitize
Publish the config file (if needed):
php artisan vendor:publish --provider="Webpatser\Sanitize\SanitizeServiceProvider"
Basic Usage: Sanitize user input in a controller or form request:
use Webpatser\Sanitize\Sanitize;
$cleanInput = Sanitize::clean($userInput);
First Use Case: Sanitize HTML input from a form before saving to the database:
$userComment = Sanitize::clean($request->input('comment'), 'html');
config/sanitize.php for custom rules and settings.app/Providers/SanitizeServiceProvider.php (if extended).Form Request Sanitization:
Extend Illuminate\Foundation\Http\FormRequest and sanitize inputs in prepareForValidation:
public function prepareForValidation()
{
$this->merge([
'comment' => Sanitize::clean($this->comment, 'html'),
]);
}
Model Observers: Sanitize attributes before saving:
public function saving(Model $model)
{
if (isset($model->comment)) {
$model->comment = Sanitize::clean($model->comment, 'html');
}
}
API Requests: Sanitize JSON payloads in middleware or controllers:
$sanitizedData = collect($request->all())
->mapWithKeys(fn($value, $key) => [$key => Sanitize::clean($value, 'text')]);
Laravel Validation: Combine with validation rules:
$validated = $request->validate([
'comment' => 'required|string|sanitize:html',
]);
(Note: Requires custom validation rule; see "Gotchas" for implementation.)
Blade Templates: Sanitize dynamic content before rendering:
{{ Sanitize::clean($userInput, 'html') }}
Queue Jobs: Sanitize data in job handlers to ensure consistency:
public function handle()
{
$cleanData = Sanitize::clean($this->data, 'text');
// Process $cleanData
}
Archived Package:
htmlpurifier/htmlpurifier or Laravel's built-in Str::of($string)->ascii() for basic sanitization.Custom Validation Rule:
The package doesn’t include a built-in validation rule. Create one in app/Rules/Sanitize.php:
use Webpatser\Sanitize\Sanitize;
class Sanitize implements \Illuminate\Contracts\Validation\Rule
{
public function passes($attribute, $value)
{
return Sanitize::clean($value, $this->type) === $value;
}
public function __construct(public string $type = 'text') {}
}
Usage:
'comment' => ['required', new Sanitize('html')],
Performance:
$cacheKey = 'sanitized_'.$userInput;
$cleanInput = cache()->remember($cacheKey, now()->addHours(1), fn() =>
Sanitize::clean($userInput, 'html')
);
False Positives:
<script> tags in code blocks). Test thoroughly.Log Sanitized Output: Compare raw vs. sanitized input to debug unexpected changes:
\Log::debug('Raw:', [$userInput]);
\Log::debug('Sanitized:', [Sanitize::clean($userInput, 'html')]);
Custom Rules:
Extend the package’s Sanitize class to add custom sanitization logic:
namespace App\Services;
use Webpatser\Sanitize\Sanitize as BaseSanitize;
class Sanitize extends BaseSanitize
{
public static function cleanCustom($input)
{
return parent::clean($input, 'text')
->replace(['[custom]', ']'], '');
}
}
Add Custom Sanitizers:
Override the getSanitizers() method in a custom service provider:
public function register()
{
$this->app->singleton('sanitize', function ($app) {
$sanitizers = [
'html' => new \Webpatser\Sanitize\Sanitizers\HtmlSanitizer(),
'custom' => new \App\Sanitizers\CustomSanitizer(), // Your class
];
return new \Webpatser\Sanitize\Sanitize($sanitizers);
});
}
Configuration:
Modify config/sanitize.php to disable default sanitizers or adjust allowed tags:
'sanitizers' => [
'html' => [
'allowed_tags' => ['p', 'br', 'strong', 'em', 'a[href]'],
'allowed_attributes' => ['href'],
],
],
Testing:
Mock the Sanitize facade in tests to avoid real sanitization:
Sanitize::shouldReceive('clean')->andReturn('mocked_output');
How can I help you explore Laravel packages today?