PHP code example of core45 / laravel-h-captcha

1. Go to this page and download the library: Download core45/laravel-h-captcha library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

core45 / laravel-h-captcha example snippets


$request->validate([
    'h-captcha-response' => [new HCaptcha],
]);

namespace Core45\HCaptcha\Contracts;

interface HostnameProvider
{
    /**
     * @return list<string>
     */
    public function hostnames(): array;
}

use Core45\HCaptcha\Contracts\HostnameProvider;
use Illuminate\Contracts\Cache\Repository as Cache;

class TenantDomainHostnameProvider implements HostnameProvider
{
    public function __construct(private Cache $cache)
    {
    }

    public function hostnames(): array
    {
        return $this->cache->remember(
            'hcaptcha.tenant-hostnames',
            now()->addMinute(),
            fn () => Shop::query()->pluck('domain')->all(),
        );
    }
}

$this->app->scoped(HostnameProvider::class, TenantDomainHostnameProvider::class);

// AppServiceProvider::boot()
\Core45\HCaptcha\HCaptchaManager::nonceUsing(fn () => \Illuminate\Support\Facades\Vite::cspNonce());

$request->validate([
    'h-captcha-response' => [new \Core45\HCaptcha\Rules\HCaptcha],
]);

$request->validate([
    'h-captcha-response' => 'hcaptcha',
]);

Route::post('/contact', ContactController::class)->middleware('hcaptcha');
Route::post('/contact', ContactController::class)->middleware('hcaptcha:my-field');

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

public string $captchaToken = '';

public function submit()
{
    $this->validate(['captchaToken' => [new \Core45\HCaptcha\Rules\HCaptcha]]);

    // ...
}

use Core45\HCaptcha\Filament\Forms\Components\HCaptcha;

HCaptcha::make() // field name defaults to config('hcaptcha.field')
    ->theme('dark')
    ->size('compact'),

// config/hcaptcha.php
'profiles' => [
    'marketing' => [
        'sitekey' => env('HCAPTCHA_MARKETING_SITEKEY'),
        'secret' => env('HCAPTCHA_MARKETING_SECRET'),
    ],
],

HCaptcha::make()->profile('marketing'),                          // Filament
new \Core45\HCaptcha\Rules\HCaptcha(profile: 'marketing'),        // validation rule

Route::post('/signup', SignupController::class)
    ->middleware('hcaptcha:h-captcha-response,,marketing');       // note the empty sitekey slot

use Core45\HCaptcha\Events\VerificationCompleted;
use Illuminate\Support\Facades\Event;

Event::listen(function (VerificationCompleted $event): void {
    if ($event->result->isConfigurationError()) {
        // alert — this is a deployment problem, not a visitor problem
    }

    Metrics::increment($event->passed() ? 'hcaptcha.passed' : 'hcaptcha.failed');
});

use Core45\HCaptcha\Facades\HCaptcha;

$result = HCaptcha::verify($request->input('h-captcha-response'), $request->ip());

if ($result->passed()) {
    // ...
}

use Illuminate\Support\Facades\Http;

Http::fake([
    'api.hcaptcha.com/*' => Http::response(['success' => true, 'hostname' => 'example.test']),
]);

$this->post('/contact', ['h-captcha-response' => 'any-token'])
    ->assertSessionHasNoErrors();

Http::assertSentCount(1); // the memoization guarantee: one token per field, one HTTP call

use Core45\HCaptcha\Facades\HCaptcha;

$hcaptcha = HCaptcha::fake(); // accepts every token from here on

$this->post('/contact', ['h-captcha-response' => \Core45\HCaptcha\Testing\FakeVerifier::TOKEN])
    ->assertSessionHasNoErrors();

$hcaptcha->assertVerifiedFor('h-captcha-response');
bash
php artisan vendor:publish --tag=hcaptcha-config       # config/hcaptcha.php
php artisan vendor:publish --tag=hcaptcha-lang         # lang/vendor/hcaptcha/{locale}/hcaptcha.php
php artisan vendor:publish --tag=hcaptcha-views        # resources/views/vendor/hcaptcha/*.blade.php
php artisan vendor:publish --tag=hcaptcha-migrations   # database/migrations/*_create_hcaptcha_verifications_table.php
bash
php artisan hcaptcha:doctor