How to Implement Simple Captcha in Laravel 10

Last Updated on by in Laravel Tutorial

Welcome to our site! If you are seeking Laravel Captcha example for adding a Captcha security (challenge-response test) to determine whether the user is a human or a robot, you’re in luck!

In this guide, we’ll explore a straightforward method to implement a CAPTCHA system within your Laravel application using the mews/captcha library, providing a crucial shield against unwanted automated activities while maintaining a seamless user experience.

“CAPTCHA” is a technology used to differentiate between human users and automated computer programs (bots) on web applications. CAPTCHA shows simple tasks on the browser screen that are easy for humans to solve but challenging for automated systems. 

This example will demonstrate how to build a basic form and enable CAPTCHA services using a PHP-based CAPTCHA library in Laravel. The Laravel CAPTCHA code example will require users to complete a simple challenge with the goal of validating that real humans are accessing systems and services while preventing malicious automated behaviors such as spamming, fraudulent activities, or unauthorized access.

A CAPTCHA, which stands for “Completely Automated Public Turing Test to tell Computers and Humans Apart,” will be integrated into the form to add an additional layer of security and validation when the form is submitted.

By implementing CAPTCHA, we can create a safer digital experience and reduce harmful bot traffic on our sites and platforms.

Let’s embark on a journey to uncover the possibilities together!

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' => [
        ...
        ...
        ...
        Mews\Captcha\CaptchaServiceProvider::class,
    ]
'aliases' => [
        ...
        ...
        ...
        'Captcha' => Mews\Captcha\Facades\Captcha::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 “Mews\Captcha\CaptchaServiceProvider” 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.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
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.

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CaptchaServiceController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
*/
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">
                        &#x21bb;
                    </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.

View on Browser

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

Laravel Captcha Tutorial - Create Captcha in Laravel

You can get the complete code from my GitHub repo.

Conclusion

By integrating Captcha in Laravel, we can ensure that only legitimate human users can access certain functionalities or submit forms on our platform.

In this tutorial, we have learned how to implement Captcha in a Laravel application using the Captcha library and easily prevent spamming, fraud, or unauthorized access.

❤️ Checkout Popular CSS Collection

Digamber - Author positronX.io

Digamber, the founder of PositronX, is a certified web developer with over 10 years of experience. He possesses a curiosity for learning new things and enjoys playing cricket on his days off.