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 Package

captcha-com/captcha

Laravel/PHP client for captcha.com. Helps you integrate CAPTCHA solving/verification into your app with simple API calls, configuration support, and helper methods for common workflows like submitting challenges and retrieving results.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require captcha-com/captcha
    

    Add the service provider and facade to config/app.php:

    'providers' => [
        // ...
        Captcha\BotDetect\BotDetectProvider::class,
    ],
    'aliases' => [
        // ...
        'Captcha' => Captcha\BotDetect\Facades\Captcha::class,
    ],
    
  2. Basic Usage Generate a CAPTCHA in a controller:

    use Captcha\Facades\Captcha;
    
    public function showForm()
    {
        $captcha = Captcha::create();
        return view('form', ['captcha' => $captcha]);
    }
    

    Render the CAPTCHA in a Blade view:

    {!! $captcha->getHtml() !!}
    
  3. Validation Validate user input in a form request or controller:

    $userInput = $request->input('captcha_code');
    if (!Captcha::validate($userInput)) {
        return back()->withErrors(['captcha' => 'Invalid CAPTCHA']);
    }
    

Implementation Patterns

Workflow: Form Protection

  1. Generate and Display

    // In controller
    $captcha = Captcha::create(['captchaType' => 'SimpleCaptcha']);
    return view('contact', ['captcha' => $captcha]);
    
    <!-- Blade -->
    <div class="captcha-container">
        {!! $captcha->getHtml() !!}
    </div>
    
  2. Validate Submission

    public function submitForm(Request $request)
    {
        $validated = $request->validate([
            'captcha_code' => 'required|captcha',
        ]);
    
        // Proceed if valid
    }
    

    (Note: The captcha rule is auto-registered by the package.)


Customization

  1. Styling Override default CSS via config (config/captcha.php):

    'captcha' => [
        'captchaType' => 'SimpleCaptcha',
        'customStyles' => [
            'backgroundColor' => '#f5f5f5',
            'fontFamily' => 'Arial',
        ],
    ],
    
  2. Advanced CAPTCHA Types Use MathCaptcha or PuzzleCaptcha for stronger protection:

    $mathCaptcha = Captcha::create(['captchaType' => 'MathCaptcha']);
    
  3. Integration with Forms Use Laravel’s form helpers for consistency:

    <form method="POST" action="/submit">
        @csrf
        <div class="captcha-container">
            {!! $captcha->getHtml() !!}
        </div>
        <input type="text" name="captcha_code" required>
        <button type="submit">Submit</button>
    </form>
    

API/Automation Use Cases

  1. Headless CAPTCHA Generation Generate a CAPTCHA for APIs without rendering HTML:

    $captcha = Captcha::create(['returnAs' => 'code']);
    $code = $captcha->getCode(); // Store in session/DB
    
  2. Dynamic CAPTCHA Refresh Refresh CAPTCHA on failed attempts:

    public function refreshCaptcha()
    {
        $captcha = Captcha::create();
        return response()->json(['html' => $captcha->getHtml()]);
    }
    
    // Frontend (e.g., AJAX)
    fetch('/refresh-captcha').then(response => {
        document.querySelector('.captcha-container').innerHTML = response.html;
    });
    

Gotchas and Tips

Pitfalls

  1. Session Expiry

    • CAPTCHA codes expire after 30 minutes by default. Adjust in config/captcha.php:
      'sessionExpiryMinutes' => 60,
      
    • Tip: Clear expired codes manually if needed:
      Captcha::clearExpiredCodes();
      
  2. Case Sensitivity

    • Validation is case-insensitive by default. Override in config:
      'caseSensitive' => true,
      
  3. CSRF Conflicts

    • Ensure @csrf is included in forms. The package does not handle CSRF protection.
  4. Image Paths

    • Default image paths may break in shared hosting. Set a custom path:
      'imagePath' => storage_path('app/captcha'),
      
    • Tip: Use php artisan storage:link if storing in public.

Debugging

  1. Validation Failures

    • Log the expected code for debugging:
      $captcha = Captcha::create();
      logger("Expected CAPTCHA: " . $captcha->getCode());
      
    • Check for typos in form field names (captcha_code is default).
  2. Image Not Displaying

    • Verify imagePath is writable:
      chmod -R 755 storage/app/captcha
      
    • Check PHP’s open_basedir restrictions if using shared hosting.
  3. Performance

    • Avoid generating CAPTCHAs in loops. Cache the HTML if reused:
      $captchaHtml = Cache::remember('captcha_html', 30, function () {
          return Captcha::create()->getHtml();
      });
      

Extension Points

  1. Custom CAPTCHA Logic Extend the base Captcha class:

    namespace App\Captcha;
    
    use Captcha\BotDetect\Captcha as BaseCaptcha;
    
    class CustomCaptcha extends BaseCaptcha
    {
        public function __construct()
        {
            parent::__construct(['customOption' => true]);
        }
    }
    

    Register in config/captcha.php:

    'captchaClass' => App\Captcha\CustomCaptcha::class,
    
  2. Event Hooks Listen for CAPTCHA generation/validation:

    // In a service provider
    Captcha::onGenerate(function ($captcha) {
        logger("CAPTCHA generated: " . $captcha->getCode());
    });
    
  3. Multi-Language Support Localize CAPTCHA text (e.g., math problems):

    $captcha = Captcha::create([
        'language' => 'es', // Spanish
        'mathOperators' => ['+', '-', '×'],
    ]);
    

Pro Tips

  • Rate Limiting: Combine with Laravel’s throttle middleware to limit CAPTCHA refreshes.
  • Accessibility: Add aria-label to CAPTCHA containers for screen readers:
    <div class="captcha-container" aria-label="CAPTCHA verification">
        {!! $captcha->getHtml() !!}
    </div>
    
  • Testing: Use Captcha::fake() in PHPUnit to mock CAPTCHAs:
    public function test_captcha_validation()
    {
        Captcha::fake('test123');
        $this->post('/submit', ['captcha_code' => 'test123'])->assertRedirect('/success');
    }
    
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.
3mdikram/worldmoneywords
snowsoft/config
itmosoft/laravel-subscriptions
larva/laravel-ai-qwen
diephp/sequences
users-au/socialite-provider
twidpay/twid-logger
mrnewport/laravel-plaid
mrnewport/laravel-repo
mrnewport/laravel-docsign
mrnewport/laravel-stow
mrnewport/laravel-flow
mrnewport/laravel-priceable
mrnewport/laravel-nestedterms
fredmeng/laravel-apidoc-generator
itstructure/laravel-multilingual-tools
pdustdar/elasticsearch
markupai/php-sdk
rlacerda83/lumem-microservice-shipment
uni-method/symfony-lib