Register Form with Captcha Code in Laravel 11
Configure Laravel Project:
Install the brand new Laravel project by typing the following command.
composer create-project --prefer-dist laravel/laravel laravelcaptcha
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
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()]); } }
Define Routes
We list the route in routes >> web.php file. So let us do it.
Route::group(['namespace' => 'App\Http\Controllers\Auth'],function() { // ----------------------------login--------------------------------// Route::controller(LoginController::class)->group(function () { Route::get('/login', 'login')->name('login'); Route::post('/login', 'authenticate'); Route::get('/logout', 'logout')->name('logout'); }); // ------------------------- register ------------------------------// Route::controller(RegisterController::class)->group(function () { Route::get('/register', 'create')->name('register'); Route::post('/register','captchaValidate')->name('register'); Route::get('refresh/captcha','refreshCaptcha')->name('refresh/captcha'); }); });
Create one view file
Create a file in the resources >> views >> captchacreate.blade.php and set the following code.
<span class="captcha">{!! captcha_img() !!}</span> <button type="button" class="btn btn-success"><i class="fa fa-refresh" id="refresh"></i></button> <script type="text/javascript"> $('#refresh').click(function(){ $.ajax({ type:'GET', url:'refresh/captcha', success:function(data){ $(".captcha").html(data.captcha); } }); }); </script>
Custom captcha
Then move to config >> captcha.php file and change the below code:
<?php use Illuminate\Support\Str; return [ "default" => [ "length" => 3, "width" => 120, "height" => 36, "quality" => 90, "math" => true, "expire" => 60, "encrypt" => false, ], ];
Clear Cache:
php artisan optimize
Serve the Application:
Finally, you can use the following command to start the Laravel development server:
php artisan serve
This will make your application accessible http://localhost:8000 by default.
Read more document:https://github.com/mewebstudio/captcha