The term was coined in 2003 by Luis von Ahn, Manuel Blum, Nicholas J. Hopper, and John Langford. The most common type of CAPTCHA was first invented in 1997 by two groups working in parallel.
Every day we receive tons of bot messages to protect this reluctant traffic and to sustain the upper-security layer of any form. We give a small challenge to real users to solve the captcha code. Well, this can’t be solved by fake users. So, to receive accurate information across the internet, we reckon the power of captcha.
Getting Started
If you have already installed the Laravel application, skip this step; otherwise, install the fresh Laravel application.
composer create-project laravel/laravel --prefer-dist laravel-captcha-generate
Next, head over to the project folder:
cd laravel-captcha-generate
Install Captcha Module
This is the foundational step of this tutorial. In this step, we will install the Captcha package using the Composer package manager.
composer require mews/captcha
Setting Up Captcha Package
Captcha package needs to be registered in laravel application. Incorporate the Captcha service provider in the laravel app.
Open providers/config/app.php file and register the captcha service provider and aliases.
'providers' => [
...
...
...
MewsCaptchaCaptchaServiceProvider::class,
]
'aliases' => [
...
...
...
'Captcha' => MewsCaptchaFacadesCaptcha::class,
]
Captcha Custom Config Settings
To manifest the custom captcha configuration, you must execute the below command:
php artisan vendor:publish
A list of options manifests on your terminal screen, select the “MewsCaptchaCaptchaServiceProvider” list number and press enter.
Inside the config/captcha.php file, here you can enable or disable settings based on your requirement.
return [
'default' => [
'length' => 5,
'width' => 120,
'height' => 36,
'quality' => 90,
'math' => true, //Enable Math Captcha
'expire' => 60, //Stateless/API captcha expiration
],
// ...
];
Create Captcha Controller
In this step you have to generate a captcha controller.
php artisan make:controller CaptchaServiceController
Incorporate the given below code in app/Http/Controllers/CaptchaServiceController.php file.
namespace AppHttpControllers;
use IlluminateHttpRequest;
class CaptchaServiceController extends Controller
{
public function index()
{
return view('index');
}
public function capthcaFormValidate(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required|email',
'username' => 'required',
'captcha' => 'required|captcha'
]);
}
public function reloadCaptcha()
{
return response()->json(['captcha'=> captcha_img()]);
}
}
index() – It loads the form template in the view with the captcha element.
capthcaFormValidate() – Validates the entire form, including the captcha input field.
reloadCaptcha() – It refreshes the captcha code or text.
Create Routes
Create three routes, to load the form with captcha, validate captcha and refresh the captcha.
Include the following code in routes/web.php file.
use IlluminateSupportFacadesRoute;
use AppHttpControllersCaptchaServiceController;
Route::get('/contact-form', [CaptchaServiceController::class, 'index']);
Route::post('/captcha-validation', [CaptchaServiceController::class, 'capthcaFormValidate']);
Route::get('/reload-captcha', [CaptchaServiceController::class, 'reloadCaptcha']);
Create Form View
At last we need to create a resources/views/index.blade.php file. Than, add the given code inside of it.
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
<link rel="stylesheet" type="text/css"
href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Styles -->
<style>
.container {
max-width: 500px;
}
.reload {
font-family: Lucida Sans Unicode
}
</style>
</head>
<body>
<div class="container mt-5">
<h2>Laravel Captcha Code Example</h2>
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div><br />
@endif
<form method="post" action="{{url('captcha-validation')}}">
@csrf
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name">
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email">
</div>
<div class="form-group">
<label for="Password">Username</label>
<input type="text" class="form-control" name="username">
</div>
<div class="form-group mt-4 mb-4">
<div class="captcha">
<span>{!! captcha_img() !!}</span>
<button type="button" class="btn btn-danger" class="reload" id="reload">
&
</button>
</div>
</div>
<div class="form-group mb-4">
<input id="captcha" type="text" class="form-control" placeholder="Enter Captcha" name="captcha">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</div>
</form>
</div>
</body>
<script type="text/javascript">
$('#reload').click(function () {
$.ajax({
type: 'GET',
url: 'reload-captcha',
success: function (data) {
$(".captcha span").html(data.captcha);
}
});
});
</script>
</html>
We imported the Bootstrap 5 beta version and a jQuery link. Then, I created a simple contact form that also heralds about captcha with a dynamic captcha refresh button.
Final Testing
Eventually, we have to run the following command to start the application.
php artisan serve
Open the captcha form using the following URL:
http://127.0.0.1:8000/contact-form
You can get the complete code from my GitHub repo.