Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Sanitize Laravel Package

webpatser/laravel-sanitize

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require webpatser/laravel-sanitize
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Webpatser\Sanitize\SanitizeServiceProvider"
    
  2. Basic Usage: Sanitize user input in a controller or form request:

    use Webpatser\Sanitize\Sanitize;
    
    $cleanInput = Sanitize::clean($userInput);
    
  3. First Use Case: Sanitize HTML input from a form before saving to the database:

    $userComment = Sanitize::clean($request->input('comment'), 'html');
    

Where to Look First

  • Documentation: Check the GitHub README for basic usage and configuration.
  • Config File: config/sanitize.php for custom rules and settings.
  • Service Provider: app/Providers/SanitizeServiceProvider.php (if extended).

Implementation Patterns

Common Workflows

  1. Form Request Sanitization: Extend Illuminate\Foundation\Http\FormRequest and sanitize inputs in prepareForValidation:

    public function prepareForValidation()
    {
        $this->merge([
            'comment' => Sanitize::clean($this->comment, 'html'),
        ]);
    }
    
  2. Model Observers: Sanitize attributes before saving:

    public function saving(Model $model)
    {
        if (isset($model->comment)) {
            $model->comment = Sanitize::clean($model->comment, 'html');
        }
    }
    
  3. API Requests: Sanitize JSON payloads in middleware or controllers:

    $sanitizedData = collect($request->all())
        ->mapWithKeys(fn($value, $key) => [$key => Sanitize::clean($value, 'text')]);
    

Integration Tips

  • 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
    }
    

Gotchas and Tips

Pitfalls

  1. Archived Package:

    • The package is archived (no active maintenance). Use with caution in production.
    • Consider alternatives like htmlpurifier/htmlpurifier or Laravel's built-in Str::of($string)->ascii() for basic sanitization.
  2. 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')],
    
  3. Performance:

    • Sanitizing large inputs (e.g., long text fields) can be slow. Cache results if reused:
      $cacheKey = 'sanitized_'.$userInput;
      $cleanInput = cache()->remember($cacheKey, now()->addHours(1), fn() =>
          Sanitize::clean($userInput, 'html')
      );
      
  4. False Positives:

    • Over-sanitization may break legitimate HTML (e.g., <script> tags in code blocks). Test thoroughly.

Debugging

  • 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]', ']'], '');
         }
     }
    

Extension Points

  1. 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);
        });
    }
    
  2. 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'],
        ],
    ],
    
  3. Testing: Mock the Sanitize facade in tests to avoid real sanitization:

    Sanitize::shouldReceive('clean')->andReturn('mocked_output');
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope