A CAPTCHA is a type of challenge–response test used in computing to determine whether or not the user is human.


Follow some steps to add captcha in your laravel form with validation:


Step 1: Getting Started

If you have already installed the Laravel application, skip this step; otherwise, install the fresh Laravel application.


composer create-project --prefer-dist laravel/laravel:^7.0 blog


Next, head over to the project folder:


cd blog


Step 2: Install Captcha Module

 Captcha package using the Composer package manager.


composer require mews/captcha


Step 3: Setting Up Captcha Package

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,
    ]


Step 3: Captcha Custom Config Settings

To manifest the custom captcha configuration


php artisan vendor:publish




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,   //captcha expiration
    ],
    // there are many type of captcha ...
];



Step 4: Create Captcha Controller

In this step you have to generate a captcha controller.


php artisan make:controller CaptchaController


app/Http/Controllers/CaptchaController.php


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CaptchaController 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()]);
    }

}



Step 5: Create Routes

Create three routes


<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CaptchaController;

/*
|--------------------------------------------------------------------------
*/


Route::get('/contact-form', [CaptchaController::class, 'index']);
Route::post('/captcha-validation', [CaptchaController::class, 'capthcaFormValidate']);
Route::get('/reload-captcha', [CaptchaController::class, 'reloadCaptcha']);


Step 6: Create view

Create contact form with captcha


resources/views/index.blade.php

<!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: 800px;
            }
            .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-success 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>


Step 7: Finally run your application


php artisan serve


http://127.0.0.1:8000/contact-form


Output: