Skip to main content
Back to packages
2,573 GitHub stars

mewebstudio/captcha

View on GitHub

Description

A simple Laravel service provider for including the Captcha for Laravel.

Session Mode:

// [your site path]/Http/routes.php
Route::any('captcha-test', function() {
if (request()->getMethod() == 'POST') {
$rules = ['captcha' => 'required|captcha'];
$validator = validator()->make(request()->all(), $rules);
if ($validator->fails()) {
echo '<p style="color: #ff0000;">Incorrect!</p>';
} else {
echo '<p style="color: #00ff30;">Matched :)</p>';
}
}
 
$form = '<form method="post" action="captcha-test">';
$form .= '<input type="hidden" name="_token" value="' . csrf_token() . '">';
$form .= '<p>' . captcha_img() . '</p>';
$form .= '<p><input type="text" name="captcha"></p>';
$form .= '<p><button type="submit" name="check">Check</button></p>';
$form .= '</form>';
return $form;
});

Detailed Example in Laravel way view files

//register.blade.php
<img src="{{ captcha_src() }}" alt="captcha">
<div class="mt-2"></div>
<input
type="text" name="captcha" class="form-control @error('captcha') is-invalid @enderror" placeholder="Please Insert Captch"
>
@error('captcha')
<div class="invalid-feedback">{{ $message }}</div> @enderror

controller files

Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => [
'required',
'string',
'email',
'max:255',
Rule::unique(User::class),
],
'password' => $this->passwordRules(),
'captcha' => 'required|captcha'
])->validate();

Stateless Mode:

You get key and img from this url http://localhost/captcha/api/math and verify the captcha using this method:

//key is the one that you got from json response
// fix validator
// $rules = ['captcha' => 'required|captcha_api:'. request('key')];
$rules = ['captcha' => 'required|captcha_api:'. request('key') . ',math'];
$validator = validator()->make(request()->all(), $rules);
if ($validator->fails()) {
return response()->json([
'message' => 'invalid captcha',
]);
 
} else {
//do the job
}

Recent Courses on Laravel Daily

Next.js Basics for Laravel Developers

11 lessons
58 min

Laravel 13 Starter Kit Teams and Customizations

10 lessons
33 min

Queues in Laravel 13

18 lessons
1 h 12 min read

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.