How to Add and Use Captcha in Laravel 10

How to Add and Use 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

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

One reply to How to Add and Use Captcha in Laravel 10

  1. It works perfect. Thank you very much for sharing your code and knowledge. I was testing with Google ReCaptcha Enterprise but it is a real headache in Laravel. Now with this solution I could do it very easily.

Leave a Reply

Your email address will not be published. Required fields are marked *