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 Profanity Filter Laravel Package

waad/laravel-profanity-filter

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation

    composer require waad/laravel-profanity-filter
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Waad\ProfanityFilter\ProfanityFilterServiceProvider"
    
  2. Basic Usage Filter text in a controller or blade view:

    use Waad\ProfanityFilter\Facades\ProfanityFilter;
    
    $cleanText = ProfanityFilter::filter('This is a bad word!');
    // Output: "This is a *** word!"
    
  3. Configuration Check config/profanity-filter.php for default settings (e.g., mask, allowed_words, languages).


First Use Case

Filter User-Generated Content

  • Scenario: A comment system where users submit text.
  • Implementation:
    // In a CommentController
    public function store(Request $request) {
        $validated = $request->validate(['content' => 'required|string']);
        $cleanContent = ProfanityFilter::filter($validated['content']);
        Comment::create(['content' => $cleanContent]);
    }
    

Implementation Patterns

Core Workflows

  1. Filtering Text

    // Basic filter
    ProfanityFilter::filter('H3ll0 w0rld!');
    
    // Custom mask (e.g., replace with "****")
    ProfanityFilter::setMask('****')->filter('badword');
    
    // Case sensitivity
    ProfanityFilter::setCaseSensitive(true)->filter('BadWord');
    
  2. Language Support

    // Switch languages dynamically
    ProfanityFilter::setLanguage('fr')->filter('Merde!');
    // Output: "****!"
    
  3. Custom Word Lists

    // Add custom words
    ProfanityFilter::addWords(['customword1', 'customword2']);
    ProfanityFilter::filter('This is customword1');
    
  4. Validation Integration

    use Illuminate\Validation\Rule;
    
    $request->validate([
        'bio' => [
            'required',
            Rule::function('filter', function ($attribute, $value, $fail) {
                if (ProfanityFilter::containsProfanity($value)) {
                    $fail('Profanity detected.');
                }
            }),
        ],
    ]);
    

Integration Tips

  • Middleware for API/Forms Create middleware to auto-filter incoming requests:

    // app/Http/Middleware/FilterProfanity.php
    public function handle($request, Closure $next) {
        $request->merge([
            'clean_content' => ProfanityFilter::filter($request->content)
        ]);
        return $next($request);
    }
    
  • Blade Directives Add a Blade directive for frontend filtering:

    // In a service provider
    Blade::directive('filter', function ($expression) {
        return "<?php echo Waad\ProfanityFilter\Facades\ProfanityFilter::filter($expression); ?>";
    });
    

    Usage:

    @filter($user->comment)
    
  • Queue Delayed Filtering For performance, defer filtering to a queue job:

    // Dispatch after saving raw data
    FilterProfanityJob::dispatch($user->id);
    

Gotchas and Tips

Pitfalls

  1. False Positives

    • Custom word lists may flag innocent terms (e.g., "bad" in "badminton").
    • Fix: Use ProfanityFilter::addAllowedWords(['badminton']) or adjust the word list.
  2. Leet Speak Detection

    • Default leet speak support may miss variations (e.g., "h3ll0" vs. "h3ll00").
    • Fix: Extend the leet speak rules in config/profanity-filter.php:
      'leet_speak' => [
          'h' => ['3', '4', 'a', 'e'],
          'e' => ['3'],
          // ...
      ],
      
  3. Performance with Large Texts

    • Filtering long strings (e.g., books) can be slow.
    • Fix: Cache filtered results or use chunking:
      $text = str_split($longText, 1000);
      array_map([ProfanityFilter::class, 'filter'], $text);
      
  4. Case Sensitivity Quirks

    • Default is case-insensitive, which may miss capitalized profanity.
    • Fix: Enable case sensitivity:
      ProfanityFilter::setCaseSensitive(true);
      

Debugging

  1. Check Filtered Output Use ProfanityFilter::getFilteredText() to inspect replacements:

    $filtered = ProfanityFilter::filter('test');
    dd(ProfanityFilter::getFilteredText());
    
  2. Log Detected Profanity Override the filter method to log matches:

    ProfanityFilter::extend(function ($text) {
        $matches = ProfanityFilter::getDetectedWords();
        \Log::info('Profanity detected:', $matches);
        return $text;
    });
    
  3. Test Edge Cases

    • Test with mixed languages (e.g., "putain" in English mode).
    • Test with symbols/numbers (e.g., "b@d" or "1337").

Extension Points

  1. Custom Filter Strategies Replace the default filter with a closure:

    ProfanityFilter::setFilterStrategy(function ($text, $words) {
        return str_replace($words, 'CENSORED', $text);
    });
    
  2. Database-Backed Word Lists Fetch words dynamically from a DB table:

    $customWords = DB::table('profanity_words')->pluck('word')->toArray();
    ProfanityFilter::addWords($customWords);
    
  3. API Wrapper for External Services Integrate with external APIs (e.g., PerspectAPI) for advanced moderation:

    ProfanityFilter::extend(function ($text) {
        $externalCheck = ExternalApi::check($text);
        return $externalCheck['safe'] ? $text : ProfanityFilter::filter($text);
    });
    
  4. Event-Based Filtering Trigger events before/after filtering:

    ProfanityFilter::listen('beforeFilter', function ($text) {
        // Pre-process text
    });
    
    ProfanityFilter::listen('afterFilter', function ($text) {
        // Post-process text
    });
    
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