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 + timed submission check. Add the x-honeypot Blade component (or pass values manually for Inertia) and the package will reject requests with filled honeypot fields or unrealistically fast submits.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation:

    composer require spatie/laravel-honeypot
    

    Publish the config file (optional):

    php artisan vendor:publish --provider="Spatie\Honeypot\HoneypotServiceProvider" --tag="honeypot-config"
    
  2. Add Honeypot to a Form: Include the Blade component in your form:

    <form method="POST" action="{{ route('contact.submit') }}">
        <x-honeypot />
        <!-- Your form fields -->
    </form>
    
  3. Apply Middleware: Protect the route handling the form submission:

    Route::post('/contact', [ContactController::class, 'store'])
        ->middleware(\Spatie\Honeypot\ProtectAgainstSpam::class);
    

First Use Case

Scenario: Protect a contact form from spam submissions.

  • Add <x-honeypot /> to the form.
  • Apply the middleware to the form submission route.
  • Test with a bot (e.g., this tool) to verify spam detection.

Implementation Patterns

Core Workflows

  1. Blade Integration:

    • Use <x-honeypot /> or @honeypot directive for standard Blade forms.
    • For Inertia/Vue, manually inject honeypot data via controllers:
      return inertia('FormPage', [
          'honeypot' => \Spatie\Honeypot\Honeypot::class,
      ]);
      
      Render in Vue:
      <div v-if="honeypot.enabled">
          <input type="text" v-model="form[honeypot.nameFieldName]" :name="honeypot.nameFieldName" />
          <input type="text" v-model="form[honeypot.validFromFieldName]" :value="honeypot.encryptedValidFrom" />
      </div>
      
  2. Livewire Integration:

    • Add the UsesSpamProtection trait to your component.
    • Declare HoneypotData property and call protectAgainstSpam() in submission logic:
      use Spatie\Honeypot\Http\Livewire\Concerns\{UsesSpamProtection, HoneypotData};
      
      class ContactForm extends Component {
          use UsesSpamProtection, HoneypotData;
      
          public function mount() {
              $this->extraFields = new HoneypotData();
          }
      
          public function submit() {
              $this->protectAgainstSpam(); // Throws exception if spam detected
              // Process form...
          }
      }
      
    • Use <x-honeypot livewire-model="extraFields" /> in Blade.
  3. Global Middleware:

    • Register ProtectAgainstSpam in app/Http/Kernel.php for all routes:
      protected $middleware = [
          // ...
          \Spatie\Honeypot\ProtectAgainstSpam::class,
      ];
      
    • Warning: Only use this if all forms include <x-honeypot />.
  4. Custom Spam Responses:

    • Implement Spatie\Honeypot\SpamResponder\SpamResponder:
      use Spatie\Honeypot\SpamResponder\SpamResponder;
      
      class CustomResponder implements SpamResponder {
          public function respond(): void {
              abort(403, 'Spam detected!');
          }
      }
      
    • Update config:
      'respond_to_spam_with' => \App\SpamResponders\CustomResponder::class,
      

Integration Tips

  • Form Validation: Combine with Laravel’s validation (e.g., required rules) for user-facing fields.
  • Testing: Use Spatie\Honeypot\Tests\TestCases\HoneypotTestCase for unit tests.
  • CSP Compliance: Enable with_csp in config and install spatie/laravel-csp to handle inline styles for hidden fields.

Gotchas and Tips

Pitfalls

  1. Missing Honeypot Fields:

    • If using global middleware (honeypot_fields_required_for_all_forms: true), all forms must include <x-honeypot />. Omitting it will flag legitimate submissions as spam.
    • Fix: Exclude specific routes via middleware groups or disable the global setting.
  2. Timestamp Validation:

    • The default amount_of_seconds: 1 may block legitimate users with fast connections. Increase this value (e.g., 5) if users report false positives.
    • Debugging: Check valid_from_timestamp in submitted data to verify timing logic.
  3. Inertia/Livewire Edge Cases:

    • Inertia: Ensure the honeypot object is passed to every form page. Forgetting it causes missing fields.
    • Livewire: The HoneypotData property must be initialized in mount() and referenced in Blade (livewire-model="extraFields").
  4. CSRF Conflicts:

    • The honeypot fields are automatically excluded from CSRF protection by the package. No additional config is needed.
  5. Dynamic Forms:

    • If forms are generated dynamically (e.g., via JavaScript), ensure <x-honeypot /> is rendered before form submission. Use AJAX pre-submission checks if needed.

Debugging

  • Log Spam Attempts: Wrap the middleware in a try-catch to log spam:

    try {
        $this->middleware(ProtectAgainstSpam::class)->handle($request);
    } catch (\Spatie\Honeypot\Exceptions\SpamException $e) {
        \Log::warning('Spam detected', ['data' => $request->all()]);
        throw $e;
    }
    
  • Verify Field Names: Check config/honeypot.php for name_field_name and valid_from_field_name. Mismatches (e.g., due to caching) cause false negatives.

  • Test with Real Bots: Use tools like Sucuri SiteCheck to simulate bot submissions and validate detection.

Extension Points

  1. Custom Field Names: Override config values dynamically:

    config(['honeypot.name_field_name' => 'custom_name_' . uniqid()]);
    
  2. Conditional Protection: Disable honeypot for specific routes:

    Route::post('/admin/contact', [ContactController::class])
        ->middleware('honeypot:disable'); // Custom middleware to skip protection
    
  3. Whitelisting IPs: Extend ProtectAgainstSpam to bypass checks for trusted IPs:

    public function handle($request, Closure $next) {
        if ($this->isTrustedIp($request->ip())) {
            return $next($request);
        }
        // ... rest of logic
    }
    
  4. Rate Limiting: Combine with Laravel’s rate limiting to throttle spam further:

    Route::post('/contact', [ContactController::class])
        ->middleware(['honeypot', 'throttle:10,1']);
    

Pro Tips

  • Performance: The package adds minimal overhead (~1ms per request). Benchmark with honeypot.enabled: false to isolate impact.
  • A/B Testing: Use randomize_name_field_name: true to vary honeypot field names and reduce bot adaptation.
  • Analytics: Track spam attempts via middleware logging to identify bot patterns (e.g., repeated submissions from specific IPs).
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport