How to Add and Use Captcha in Laravel 10

1. Install the Laravel Captcha Package

First, you need to install the Laravel Captcha package using the Composer package manager. Open the terminal and run the following command:

composer require anhskohbo/no-captcha

2. Add Service Provider

After installing the package, you need to add the service provider to the providers array in the config/app.php file.

Anhskohbo\NoCaptcha\NoCaptchaServiceProvider::class,

3. Add Facade

You also need to add the Facade to the aliases array in the config/app.php file.

‘NoCaptcha’ => Anhskohbo\NoCaptcha\Facades\NoCaptcha::class,

4. Publish Configuration File

Now, you need to publish the configuration file. Run the following command in the terminal:

php artisan vendor:publish –provider=”Anhskohbo\NoCaptcha\NoCaptchaServiceProvider”

5. Configure Captcha

Now, you need to configure the captcha. Open the config/captcha.php file and add your site key and secret key.

‘captcha_site_key’ => ‘YOUR_SITE_KEY’,

‘captcha_secret_key’ => ‘YOUR_SECRET_KEY’,

6. Add Captcha to Form

Now, you need to add the captcha to the form. Open the view file and add the following code:

{!! NoCaptcha::renderJs() !!}

{!! NoCaptcha::display() !!}

7. Validate Captcha

Now, you need to validate the captcha. Open the controller file and add the following code:

$validator = Validator::make($request->all(), [

‘g-recaptcha-response’ => ‘required|captcha’,

]);

if ($validator->fails()) {

// Captcha validation failed

} else {

// Captcha validation passed

}

8. Add Error Message

Now, you need to add the error message. Open the resources/lang/en/validation.php file and add the following code:

‘captcha’ => ‘The :attribute field is not correct.’,

Now, you have successfully added and used captcha in Laravel 10.

Captcha is a widely used security measure in web applications to distinguish between human users and automated bots. In this tutorial, you will learn unique approach to adding and utilizing Captcha in Laravel 10 to enhance the security of your application.

How to Add and Use Captcha in Laravel 10

By using the following steps, you can add and use captcha in laravel 10 with forms:

  • Step 1 – Create New Laravel 10 Project
  • Step 2 – Setup Database with Laravel Project
  • Step 3 – Install Captcha Package
  • Step 4 – Register Captcha Package
  • Step 5 – Captcha Configuration
  • Step 6 – Define Routes
  • Step 7 – Create Form Controller and Define Methods
  • Step 8 – Add Captcha in Form
  • Step 9 – Run Development Server

Step 1 – Create New Laravel 10 Project

First of all, Open your command prompt or terminal.

Then execute the following command into it to download or install Laravel 10 new setup on your server:

composer create-project --prefer-dist laravel/laravel FormValidation

Step 2 – Setup Database with Laravel Project

Once you have installed laravel project in your server. Then you need to configure your database with your apps.

So, visit your app root directory and find .env file. Then configure database details as follows:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database-name
DB_USERNAME=database-user-name
DB_PASSWORD=database-password

Step 3 – Install Captcha Package

In this step, open again your command prompt. And run the following command on it. To install captcha package:

composer require mews/captcha

Step 4 – Register Captcha Package

In this step, registered this package in laravel application. So, 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 5 – Captcha Configuration

In this step, open config/captcha.php file. And in this file 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
    ],
    // ...
];

Step 6 – Define Routes

In this step, Visit your routes directory and open web.php file in any text editor. And add the following routes into web.php route file:

use App\Http\Controllers\CaptchaValidationController;


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




Step 7 – Create Form Controller and Define Methods

In this step, execute the following command on terminal/command prompt/command line to create controller file for your laravel applications; is as follow:

php artisan make:controller CaptchaValidationController

Now, visit your laravel directory app/http/controllers and open CaptchaValidationController.php file. And update the following code into it:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class CaptchaValidationController extends Controller
{
    public function index()
    {
        return view('form-with-captcha');
    }

    public function capthcaFormValidate(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email',
            'message' => 'required',
            'captcha' => 'required|captcha'
        ]);
    }

    public function reloadCaptcha()
    {
        return response()->json(['captcha'=> captcha_img()]);
    }

}

Step 8 – Add Captcha in Form

Now, create blade view file to display form with captcha challenge and submit to database. So, Go to resources/views and create form-with-captcha.blade.php and update the following code into it:

<!DOCTYPE html>
<html>
<head>
<title>Laravel 10 Form Captcha Validation</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-4">
@if(session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
@endif
<div class="card">
<div class="card-header text-center font-weight-bold">
<h2>Laravel 10 Add Captcha in Form For Validation</h2>
</div>
<div class="card-body">
<form name="captcha-contact-us" id="captcha-contact-us" method="post" action="{{url('captcha-validation')}}">
@csrf
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="text" id="name" name="name" class="@error('name') is-invalid @enderror form-control">
@error('name')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
@enderror
</div>          
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input type="email" id="email" name="email" class="@error('email') is-invalid @enderror form-control">
@error('email')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
@enderror
</div>              
<div class="form-group">
<label for="exampleInputEmail1">Message</label>
<textarea name="message" class="@error('message') is-invalid @enderror form-control"></textarea>
@error('message')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
@enderror
</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>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>	
<script type="text/javascript">
$('#reload').click(function () {
$.ajax({
type: 'GET',
url: 'reload-captcha',
success: function (data) {
$(".captcha span").html(data.captcha);
}
});
});
</script>
</body>
</html>

The following below code will display validation error message on blade view file:

@error('name')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
@enderror

Step 9 – Run Development Server

Last step, open command prompt and run the following command to start developement server:

php artisan serve

Then open your browser and hit the following url on it:

http://127.0.0.1:8000/contact-form-captcha

Conclusion

By following this tutorial, you will gain a thorough understanding of how to add and utilize Captcha in your Laravel 10 application. This additional security measure will protect your forms from spam, brute-force attacks, and other malicious activities.

Recommended Laravel Posts

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?