Author - StudySection Post Views - 129 views
Captcha

How to build your own Captcha for security in your Laravel application.

To stop brute force attacks into our application captcha is needed.
Most of the developers use google services for this security. But still, there are many developers who did not trust the third-party services for security purposes they build their own captcha.

mewebstudio/captcha Laravel package is very simple and easy to integrate in our project.

composer require mews/captcha
In the root directory of your laravel project run the above command in the terminal to install the package. And then configure the package with the following steps.
Open the config/app.php file and add this line
‘Mews\Captcha\CaptchaServiceProvider’, Into the providers array.
And this
‘Captcha’ => ‘Mews\Captcha\Facades\Captcha’,

Into the aliases array in the same file.
After this run the below command on the terminal :
php artisan vendor:publish
Now all the vendor files will be published. config/captcha.php file is now generated.
To refresh the generated captcha add routes for that in the web.php file.
Route::get('refresh-captcha',
'ContactController@refreshCaptcha')->name('refreshCaptcha');

In the controller add the below line
use Captcha;
To validate captcha you can use the following code in your form submission code
$this->validate($request, [
'captcha' => 'required|captcha', // validate captcha]);

After this you can write your code that will run if your captcha is validated.
public function refreshCaptcha()
{
return response()->json([
'captcha' => Captcha::img()
]);
}

The above code is used to refresh the captcha if needed.
Now in the view file, you can add the HTML for the captcha image.
<div class="form-group row">
<label for="captcha" class="col-md-4 col-form-label text-md-right">Captcha</label>
<div class="col-md-6">
<span class="captcha-image">{!! Captcha::img() !!}</span>
<button type="button" class="btn btn-success refreshCaptcha">Refresh captcha </button>
</div>
</div>

Captcha::img() this method will help us to load the captcha image.

And for the refresh captcha button, you can use ajax that will refresh the captcha.
$(document).ready(function() {
$('.refreshCaptcha).click(function() {
$.ajax({
type: 'get',
url: '{{ route('refreshCaptcha') }}',
success:function(data) {
$('.captcha-image').html(data.captcha);
}
});
});
});

After following all the above-mentioned steps you are able to use captcha while submitting the web forms.

The English language is the most widely used medium of communication around the world. Having a certification for the English language can be an advantage. StudySection provides an English Certification Exam that tests English language proficiency in English grammar, reading, and writing.

Leave a Reply

Your email address will not be published.