Laravel 8 captcha example; In this tutorial, you will learn how to add a captcha validation with laravel 8 forms.
Captcha Verification (or Completely Automated Public Turing Test to tell Computers and Humans Apart) is a common web technique used to help ensure that your respondents are real humans and not a program written to spam your survey. The respondent is asked to check a box to prove that they are human.
The captcha provides security challenge on forms to prevent comment spamming, form spamming.
How to Add Captcha in Laravel 8?
- Step 1 – Download Laravel 8 Application
- Step 2 – Setup Database with App
- Step 3 – Install Captcha Package
- Step 4 – Register Captcha Package
- Step 5 – Captcha Configuration
- Step 6 – Create Form Routes
- Step 7 – Create Form Controller By Artisan Command
- Step 8 – Create Form Blade File
- Step 9 – Run Development Server
Step 1 – Download Laravel 8 Application
First of all download or install laravel 8 new setup. So, open terminal and type the following command to install new laravel 8 app into your machine:
composer create-project --prefer-dist laravel/laravel FormValidation
Step 2 – Setup Database with App
In this step, setup database with your downloded/installed laravel 8 app. So, you need to find .env file and setup database details as following:
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 – Create Routes
In this step, open web.php file from routes direcotry. And update the following routes into web.php 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 By Artisan Command
In this step, run the following command on command prompt to create controller file:
php artisan make:controller CaptchaValidationController
After that, go to 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 – Create Blade File
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 8 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 8 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