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

Captcha Laravel Package

baks-dev/captcha

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require baks-dev/captcha
    
  2. Publish assets and configuration (required for templates and storage):

    php artisan baks:assets:install
    
    • This generates the public/baks/captcha/ directory and config file at config/baks/captcha.php.
  3. Basic usage in a form:

    use BaksDev\Captcha\CaptchaBuilder;
    
    // In your controller or service
    $captcha = CaptchaBuilder::build();
    $captcha->store(); // Stores in session by default
    
    // In your Blade template
    <img src="{{ $captcha->getImageUrl() }}" alt="CAPTCHA">
    <input type="text" name="captcha_code" required>
    
  4. Validate the submission:

    use BaksDev\Captcha\CaptchaValidator;
    
    $validator = CaptchaValidator::validate(request('captcha_code'));
    if (!$validator->isValid()) {
        return back()->withErrors(['captcha' => 'Invalid CAPTCHA']);
    }
    

First Use Case: Login Form

  • Add CAPTCHA to your login form to prevent brute-force attacks.
  • Store the CAPTCHA in the session and validate it alongside credentials.

Implementation Patterns

Common Workflows

1. Dynamic CAPTCHA Generation

// Generate a new CAPTCHA per request (e.g., for AJAX forms)
$captcha = CaptchaBuilder::build([
    'length' => 6, // Custom length
    'font' => 'arial.ttf', // Custom font (must be in assets)
    'width' => 120,
    'height' => 40,
]);
$captcha->store('custom_key'); // Store with a custom key

2. Integration with Laravel Forms

// Using Laravel Collective or Livewire
{!! Form::captcha() !!} // If the package provides a helper (check docs)
  • For Livewire, bind the CAPTCHA to a property and validate in rules().

3. API Usage (Headless)

// Generate CAPTCHA for API responses (e.g., as a base64 image)
$captcha = CaptchaBuilder::build();
$image = $captcha->getImage();
return response($image)->header('Content-Type', 'image/png');

4. Custom Storage

Override the default session storage:

$captcha = CaptchaBuilder::build();
$captcha->storeInDatabase($userId); // Hypothetical method (check docs)

5. ReCAPTCHA Hybrid

Combine with Google ReCAPTCHA for extra security:

// Validate both CAPTCHAs
$validator = CaptchaValidator::validate(request('captcha_code'));
$recaptcha = app('recaptcha')->verify(request('g-recaptcha-response'));

Integration Tips

Laravel Services

  • Service Provider: Register the package in AppServiceProvider if not auto-discovered:
    if (!app()->has('baks.captcha')) {
        $this->app->register(BaksDev\Captcha\CaptchaServiceProvider::class);
    }
    

Blade Directives

  • Create a custom Blade directive for reusable CAPTCHA rendering:
    Blade::directive('captcha', function ($expression) {
        $captcha = CaptchaBuilder::build();
        return "<?php echo \$captcha->render(); ?>";
    });
    
    Usage:
    @captcha
    

Middleware

  • Add CAPTCHA validation to specific routes:
    public function handle(Request $request, Closure $next) {
        if ($request->is('login') && $request->isMethod('post')) {
            $validator = CaptchaValidator::validate($request->captcha_code);
            if (!$validator->isValid()) {
                return back()->withErrors(['captcha' => 'Invalid']);
            }
        }
        return $next($request);
    }
    

Gotchas and Tips

Pitfalls

1. Asset Paths

  • Forgetting to run php artisan baks:assets:install will break image generation.
  • Fix: Ensure public/baks/captcha/ exists and is writable.

2. Session Storage

  • CAPTCHAs stored in the session expire with the session. For long-lived forms, consider:
    • Database storage (if the package supports it).
    • Regenerating the CAPTCHA on each request (e.g., AJAX forms).

3. Font Files

  • The package expects .ttf fonts in public/baks/captcha/fonts/.
  • Fix: Download a free font (e.g., from Google Fonts) and place it in the correct directory.

4. Case Sensitivity

  • Validation is case-sensitive by default. Use:
    $validator = CaptchaValidator::validate(strtolower(request('captcha_code')));
    

5. Rate Limiting

  • CAPTCHAs can be bypassed if not combined with rate limiting (e.g., Laravel's throttle middleware).

6. Caching

  • Pre-generating CAPTCHAs for performance may reduce security (e.g., if the image is cached too aggressively).

Debugging

1. Image Not Generating

  • Check storage/logs/laravel.log for errors like missing GD library.
  • Fix: Install PHP GD extension:
    sudo apt-get install php-gd  # Ubuntu/Debian
    sudo dnf install php-gd      # CentOS/RHEL
    

2. Validation Failing

  • Verify the CAPTCHA code matches exactly (including spaces/punctuation).
  • Debug: Log the stored and submitted codes:
    \Log::info('Stored:', session('captcha_code'));
    \Log::info('Submitted:', request('captcha_code'));
    

3. Configuration Overrides

  • Custom config in config/baks/captcha.php may conflict with defaults.
  • Tip: Use php artisan config:clear after changes.

Extension Points

1. Custom CAPTCHA Types

  • Extend the builder to support:
    • Math-based CAPTCHAs (e.g., 2 + 3 = ?).
    • Audio CAPTCHAs for accessibility.
class MathCaptcha extends CaptchaBuilder {
    public function build() {
        $this->setText($this->generateMathProblem());
        // ...
    }
}

2. Event Listeners

  • Listen for CAPTCHA generation/validation events (if the package supports them):
// config/baks/captcha.php
'events' => [
    'enabled' => true,
],

3. Testing

  • Mock CAPTCHA validation in tests:
$this->partialMock(CaptchaValidator::class, 'validate')
     ->shouldReceive('isValid')
     ->andReturn(true);

4. Localization

  • Add language support for hints (e.g., "Enter the characters above"):
$captcha = CaptchaBuilder::build(['locale' => 'es']);

5. Theming

  • Override the default template by publishing views:
php artisan vendor:publish --tag=baks-captcha-views
  • Customize colors/fonts in resources/views/vendor/baks/captcha.blade.php.

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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky