Weave 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

Captcha Laravel Laravel Package

mlk9/captcha-laravel

A lightweight CAPTCHA package for Laravel that adds customizable image or math challenges to your forms. Generate and validate captchas with Blade helpers, validation rules, and config options to protect your app from spam and automated bot submissions.

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Install and publish

    composer require <vendor>/<package>:^3.1
    php artisan vendor:publish --provider="<Vendor>\<Package>\<PackageServiceProvider>"
    

    If the package ships migrations/assets, publish those tags too. For the new Math Captcha driver you typically do not need image/GD assets or third-party API keys.

  2. Configure the driver Start in config/captcha.php (or the package’s equivalent). Look for the driver/type key and set it to the math option added in v3.1.1:

    'driver' => env('CAPTCHA_DRIVER', 'math'),
    

    Keep the default as your existing driver and override per form where possible.

  3. First use case: protect a public form without external dependencies Add the captcha to a contact or login form:

    <form method="POST" action="/contact">
        @csrf
        @captcha('math') {{-- or the package’s Blade directive/component --}}
        <button>Send</button>
    </form>
    

    Validate server-side:

    $request->validate([
        'captcha' => ['required', 'captcha'],
    ]);
    
  4. Where to look first

    • config/captcha.php — driver names, options, session key, route middleware.
    • The package README section for Math Captcha — exact driver string, Blade directive, and validation rule.
    • The validation rule class and the driver contract — this is your extension point if you need a custom challenge type.

Implementation Patterns

Driver-per-form Keep the image/service driver for high-risk forms and use math for low-friction forms:

// config/captcha.php
'driver' => 'recaptcha',

// In a form request or controller
$request->validate([
    'captcha' => ['required', 'captcha:math'],
]);

Confirm in the README whether the driver is selected via rule parameter, config override, or a separate Blade directive. Do not assume both approaches exist.

Form Request encapsulation

class ContactRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email'],
            'message' => ['required', 'string'],
            'captcha' => ['required', 'captcha:math'],
        ];
    }

    public function messages(): array
    {
        return [
            'captcha.captcha' => 'Please solve the math question correctly.',
        ];
    }
}

Blade usage Prefer the package directive/component over hand-writing hidden inputs. Math captchas usually render a question and an input; the package handles the signed/session-backed answer. If you need custom markup, inspect the rendered HTML in devtools and reuse the package’s field names and session keys rather than guessing.

AJAX/SPA refresh Math captchas are session-backed and usually one-time. For SPAs, expose or reuse the package’s refresh endpoint so a failed submission can request a new question:

await fetch('/captcha/refresh', { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
    .then(r => r.json())
    .then(({ question, html }) => { /* replace captcha container */ });

If the package does not ship a refresh route, add a small controller that calls the driver’s regenerate method.

Combine with layered defenses Math captcha is a low-friction bot deterrent, not a complete anti-spam solution. Pair it with:

  • Honeypot fields
  • throttle middleware on the route
  • Server-side validation of all other fields
  • Optional email/domain reputation checks

Testing Configure a bypass driver in phpunit.xml or config/captcha.php under the testing environment:

<env name="CAPTCHA_DRIVER" value="null"/>

If the package provides a fake, use it:

Captcha::fake();

For tests that intentionally exercise the math driver, submit a known answer by reading the session value or by using the package’s testing helper.

Localization and accessibility Math captchas are generally more accessible than image-only captchas, but still:

  • Localize number words if the package renders them (lang/vendor/<package>/...).
  • Keep the question text readable by screen readers.
  • Provide an alternative contact path for users who cannot solve it.

Gotchas and Tips

  • Session dependency: Math captchas store the expected answer in the session. Ensure production uses a persistent session driver (redis, database, file) and that the route has the web middleware group. The array driver will break validation across requests.
  • One-time use: Most captcha drivers consume/regenerate the challenge after validation. A failed form submission should re-render a fresh question; do not reuse the same HTML blindly in a loop.
  • Multiple forms on one page: Two captcha instances may share session keys. Check whether the package supports named instances. If not, avoid placing two captcha-protected forms on the same page, or isolate them with separate session keys.
  • Config cache: After changing the driver or publishing config, run:
    php artisan config:clear
    
    A cached config is the most common reason a new driver “doesn’t work.”
  • Rule name and driver string: The v3.1.1 notes only say “Add Math Captcha.” Verify the exact driver identifier in the README/changelog. A typo such as math-captcha vs math will usually fall back silently to the default driver.
  • No assets required for math: If you were previously using an image captcha, you can stop publishing/loading its assets for math-protected forms, but do not remove them globally until all forms are migrated.
  • CSRF and throttling: CAPTCHA does not replace CSRF protection or rate limiting. Keep @csrf and route throttle middleware in place.
  • Bot resistance limits: Simple arithmetic is solvable by determined bots. Treat math captcha as friction, not security. Use it on low-risk forms and keep stronger mechanisms on auth, password reset, and payment flows.
  • Extension points: If you need a custom challenge, look for a driver contract/interface in the package. Implement it and bind it in a service provider rather than editing vendor files.
  • Version pinning: v3.1.1 appears additive, but pin to ^3.1 and scan the changelog before jumping minors. Run your form/validation tests after upgrading, especially if you override the validation rule or Blade directive.
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.
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums
rlacerda83/query-parser
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings