Laravel 8 Captcha Code Tutorial

10-Apr-2023

.

Admin

Laravel 8 Captcha Code Tutorial

Hi Guys,

In this tutorial,I will learn you how to use captcha code in laravel 8.you can easy and simply use captcha code in laravel 8.

In this post i give you very simple and from scratch of generate captcha code image as you can also see bellow preview. After complete this example you can found ui design like bellow preview, you have to just follow few step and find result:

Step 1: Install Laravel Project


First, you need to download the laravel fresh setup. Use this command then download laravel project setup :

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

Step 2: 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

],

// ...

];

Step 3: Add Controller Method

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.

app/Http/Controllers/CaptchaController.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',

'captcha' => 'required|captcha'

]);

}

public function reloadCaptcha()

{

return response()->json(['captcha'=> captcha_img()]);

}

}

Step 4: Create Routes

Create three routes, to load the form with captcha, validate captcha and refresh the captcha.

routes/web.php

use App\Http\Controllers\CaptchaController;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!

|

*/

Route::get('contact-form', [CaptchaController::class, 'index']);

Route::post('captcha-validation', [CaptchaController::class, 'capthcaFormValidate']);

Route::get('reload-captcha', [CaptchaController::class, 'reloadCaptcha']);

Step 5: Create blade file

In this last Step,you will create to layout your file.

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>

.reload {

font-family: Lucida Sans Unicode

}

</style>

</head>

<body>

<div class="container mt-5">

<div class="row">

<div class="col-md-8">

<div class="card">

<div class="card-header">

<h2>Laravel Captcha Code Example - Nicesnippest.com</h2>

</div>

<div class="card-body">

@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 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>

<div class="form-group">

<button type="submit" class="btn btn-primary btn-block">Submit</button>

</div>

</form>

</div>

</div>

</div>

</div>

</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>

Now we are ready to run our example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/contact-form

It will help you...

#Laravel 8