Captcha stands for Completely Automated Public Turing test. It is mainly used as a security test to ensure only human users can pass through. Computers or bots are not able to solve a captcha. There are different types of captcha. Therefore, we can use some protection.
Here is the step-by-step guide to generate a captcha code in Laravel.
Step 1: Configure Laravel Project
Install the brand new Laravel project by typing the following command.
composer create-project --prefer-dist laravel/laravel laravelcaptcha
Step 2: Install the Captcha package.
We must add the Mews captcha package, so switch to your terminal and type the command below.
composer require mews/captcha
Step 3: Add Service Provider
To use the Captcha Service Provider, you must register the provider.
Find the providers in bootstrap >> providers.php file and register the Captcha Service Provider.
<?php return [ App\Providers\AppServiceProvider::class, Mews\Captcha\CaptchaServiceProvider::class, ];
Step 4: Create one controller
php artisan make:controller CaptchaController --resource
It will create one controller file called the CaptchaController.php file.
Define validation and captcha code in the controller file.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Mews\Captcha\Facades\Captcha; class CaptchaController extends Controller { /** * Show the form for creating a new resource. */ public function create() { return view('captchacreate'); } public function captchaValidate(Request $request) { $request->validate([ 'name' => 'required', 'email' => 'required|email', 'password' => 'required|min:6', 'captcha' => 'required|captcha' ]); } public function refreshCaptcha() { return response()->json(['captcha'=> captcha_img()]); } }
In the captchaValidate() function, we have put the validation. If any validation fails, it throws an error.
In the refreshCaptcha() function, we have defined the refresh code. When the user clicks on refresh, the captcha code change.
Step 5: Define Routes
We list the route in routes >> web.php file. So let us do it.
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\CaptchaController; Route::get('/', function () { return view('welcome'); }); Route::get('createcaptcha', [CaptchaController::class, 'create'])->name("captchacontroller.create"); Route::post('createcaptcha', [CaptchaController::class, 'captchaValidate'])->name("captchacontroller.captcha"); Route::get('refreshcaptcha', [CaptchaController::class, 'refreshCaptcha'])->name("captchacontroller.refresh");
In the web.php file, we define Three(3) routes: the first route for displaying the form, the second for a post request, and the third for refreshing the captcha code.
Step 6: Create one view file
Create a file in the resources >> views >> captchacreate.blade.php and set the following code.
<html lang="en"> <head> <title>Captcha Code in Laravel</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js" integrity="sha384-BBtl+eGJRgqQAUMxJ7pMwbEyER4l1g+O15P+16Ep7Q9Q+zqX6gSbd85u4mG4QzX+" crossorigin="anonymous"></script> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css", rel="stylesheet", integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN", crossorigin="anonymous"> </head> <body> <div class="container"> <h2>Captcha Code in Laravel</h2><br/> @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('createcaptcha')}}"> @csrf <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <label for="Name">Name:</label> <input type="text" class="form-control" name="name"> </div> </div></br> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <label for="Email">Email:</label> <input type="text" class="form-control" name="email"> </div> </div></br> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <label for="Password">Password:</label> <input type="password" class="form-control" name="password"> </div> </div></br> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <div class="captcha"> <span>{!! captcha_img() !!}</span> <button type="button" class="btn btn-success"><i class="fa fa-refresh" id="refresh"></i></button> </div> </div> </div></br> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <input id="captcha" type="text" class="form-control" placeholder="Enter Captcha" name="captcha"></div> </div></br> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> </div> </body> <script type="text/javascript"> $('#refresh').click(function(){ $.ajax({ type:'GET', url:'refreshcaptcha', success:function(data){ $(".captcha span").html(data.captcha); } }); }); </script> </html>
Next, Begin the Laravel Development server by hitting the following command.
php artisan serve
Move to the browser and hit this URL: http://localhost:8000/createcaptcha
We will get errors if we do not enter any fields or enter an invalid captcha code.
If you want to enable math captcha then you need to publish config.
php artisan vendor:publish
Then move to config >> captcha.php file and change the below code:
'default' => [ 'length' => 9, 'width' => 120, 'height' => 36, 'quality' => 90, 'math' => true, 'expire' => 60, 'encrypt' => false, ],
Again, start the development server, and our form looks like this:
That’s it for this tutorial.
zabi
hi
i,m from iran
very good
بسیار عالی بود
Vikas
How to get invalid captcha responce and if one time capcha is invalid the new capcha compulsory generate
Bairu
Thanks for this post. It’s very helpful and working fine. In case, I need two captcha for two different forms, How can I implement this?. Is it possible to use this or go for another.
Shankar Bhatt
refresh button is not working . can you help me?
Vladimir
Drag the id=”refresh” from the tag to the tag.
Vladimir
From the tag “i” to the tag “button”
shishir
Refresh captcha not working
Krunal Lathiya
It’s working fine from my end. Could you please provide more details?
swag
return of refreshcaptcha should be return captcha_img(); only no json is needed and yes id should be moved to the button instead of the i element
Honest Raj
It’s throws the error like ” Call to undefined function captcha_img() “. when i start to run the error appearing
Krunal Lathiya
It’s working fine from my end. Could you please provide more details?
satvinder
i m also getting error when captcha_img() is called in my view blade(laravel 6) . is this captcha compatile with laravel 6?
Krunal Lathiya
It’s working fine from my end. Could you please provide more details?
Rui M. Silva
I got everything working, and then, after working on other stuff on my project seemingly unrelated to captcha, I noticed it was no longer working, and I don’t understand why. Googled around but cannot find anything specifically related to this Laravel error on using this package.
This is an image of the error I’m getting, and I can’t figure out the reason (it seems to be about decrypting the payload, referring the payload is invalid):
If anyone can help, I’d greatly appreciate it, thanks!
Honest Raj
It’s throws the error like ” Call to undefined function captcha_img() “. when i start to run the error appearing
Krunal Lathiya
It’s working fine from my end. Could you please provide more details?