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 Honeypot Laravel Package

spatie/laravel-honeypot

Protect Laravel forms from spam bots with a simple honeypot field and submit-time check. Add the x-honeypot Blade component (or pass values manually for Inertia) and automatically discard suspicious submissions with filled traps or too-fast posts.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**: Add the package via Composer:
   ```bash
   composer require spatie/laravel-honeypot
  1. Publish Config (Optional):

    php artisan vendor:publish --provider="Spatie\Honeypot\HoneypotServiceProvider" --tag="honeypot-config"
    

    (Default config is sufficient for most use cases.)

  2. First Use Case:

    • Add the Blade component to your form:
      <form method="POST" action="{{ route('contact.submit') }}">
          <x-honeypot />
          <!-- Your form fields -->
      </form>
      
    • Apply the middleware to the form route:
      Route::post('/contact', [ContactController::class, 'store'])
           ->middleware(\Spatie\Honeypot\ProtectAgainstSpam::class);
      

Where to Look First

  • Blade Integration: Focus on <x-honeypot /> or @honeypot directives.
  • Middleware: Ensure ProtectAgainstSpam is applied to form-handling routes.
  • Config: Check config/honeypot.php for field names (name_field_name, valid_from_field_name) and thresholds.

Implementation Patterns

Core Workflow

  1. Form Protection:

    • Add <x-honeypot /> to every public form (contact, registration, etc.).
    • Apply ProtectAgainstSpam middleware to the form’s submission route/controller.
  2. Dynamic Field Names:

    • Use randomize_name_field_name (default: true) to dynamically rename honeypot fields, reducing bot detection risks.
    • Example config override:
      'name_field_name' => 'custom_honeypot_name',
      'randomize_name_field_name' => false,
      
  3. Inertia/Livewire Integration:

    • Inertia: Pass honeypot data via controllers:
      return inertia('FormPage', ['honeypot' => \Spatie\Honeypot\Honeypot::class]);
      
      Render hidden fields in Vue:
      <input v-if="honeypot.enabled" v-model="form[honeypot.nameFieldName]" type="text" :name="honeypot.nameFieldName">
      
    • Livewire: Use UsesSpamProtection trait and HoneypotData property:
      use Spatie\Honeypot\Http\Livewire\Concerns\{UsesSpamProtection, HoneypotData};
      public HoneypotData $extraFields;
      public function mount() { $this->extraFields = new HoneypotData(); }
      public function submit() { $this->protectAgainstSpam(); /* ... */ }
      
  4. Global Middleware (Caution):

    • Register globally in app/Http/Kernel.php:
      protected $middleware = [
          \Spatie\Honeypot\ProtectAgainstSpam::class,
          // ...
      ];
      
    • Warning: Only use if all forms include <x-honeypot />. Missing fields will trigger spam checks.
  5. Custom Spam Responses:

    • Extend SpamResponder to replace the default blank page:
      use Spatie\Honeypot\SpamResponder\SpamResponder;
      class CustomResponder implements SpamResponder {
          public function respond(): void { abort(403, 'Spam detected.'); }
      }
      
      Update config:
      'respond_to_spam_with' => \App\CustomResponder::class,
      

Gotchas and Tips

Pitfalls

  1. Missing Honeypot Fields:

    • If using global middleware, all forms must include <x-honeypot />. Omitting it will incorrectly flag legitimate submissions as spam.
    • Fix: Disable global middleware or ensure consistency.
  2. CSRF + Honeypot Conflicts:

    • Honeypot fields must not collide with CSRF tokens or other hidden fields (e.g., name="token").
    • Tip: Use unique names like honeypot_name_123 or leverage randomize_name_field_name.
  3. Livewire Volt Quirks:

    • In Volt, explicitly declare guessHoneypotDataProperty to avoid property resolution issues:
      $guessHoneypotDataProperty = fn() => $this->extraFields;
      
  4. Time-Based Checks:

    • The amount_of_seconds (default: 1) may be too strict for slow networks.
    • Adjust: Increase to 35 for user-friendly thresholds:
      'amount_of_seconds' => 3,
      
  5. CSP Integration:

    • Enable with_csp only if using Laravel CSP. Hidden styles may break without CSP headers.
    • Fix: Add inline styles to CSP allowlist:
      'style-src' => ['self', 'unsafe-inline'], // Temporary workaround
      

Debugging Tips

  1. Log Spam Attempts:

    • Extend SpamProtection to log failed attempts:
      use Spatie\Honeypot\Exceptions\SpamException;
      class CustomProtection extends \Spatie\Honeypot\SpamProtection {
          public function protect(Request $request) {
              try { parent::protect($request); }
              catch (SpamException $e) { \Log::warning('Spam detected', ['ip' => $request->ip()]); }
          }
      }
      
      Update config:
      'spam_protection' => \App\CustomProtection::class,
      
  2. Test Locally:

    • Simulate spam with curl:
      curl -X POST -d "my_name=spam&valid_from=123" http://your-app.test/contact
      
    • Verify the blank page response (default) or custom error.
  3. Disable Temporarily:

    • Set 'enabled' => false in config to bypass honeypot during development.

Extension Points

  1. Custom Validation:

    • Combine with Laravel’s validation to add context:
      public function store(Request $request) {
          $this->protectAgainstSpam($request);
          $validated = $request->validate([
              'honeypot_name' => 'required|empty', // Explicitly check honeypot
              'email' => 'required|email',
          ]);
      }
      
  2. Dynamic Field Names:

    • Override field names per form:
      <x-honeypot :name="'contact_honeypot'" :valid-from="'contact_timestamp'" />
      
      (Requires custom Blade component or config overrides.)
  3. Rate Limiting:

    • Pair with throttle middleware to block repeated spam:
      Route::post('/contact')->middleware([
          \Spatie\Honeypot\ProtectAgainstSpam::class,
          \Illuminate\Routing\Middleware\ThrottleRequests::class . ':5,1',
      ]);
      
  4. CAPTCHA Fallback:

    • Use honeypot as a first line of defense, then require CAPTCHA (e.g., hCaptcha) for suspicious submissions.
    • Example:
      try { $this->protectAgainstSpam($request); }
      catch (SpamException $e) { return redirect()->route('contact')->with('captcha_required', true); }
      

---
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony