Laravel 7.x Recaptcha

Sujith Sandeep
2 min readJun 7, 2020

--

Recaptcha is a functionality that helps to protect the website from spam and abuse.

Installation :

Please get the dependencies using the below link in terminal,

composer require mews/captcha

Setup :

Find the providers key in config/app.php and register the Captcha Service Provider.

'providers' => [
Mews\Captcha\CaptchaServiceProvider::class,
]
'aliases' => [
'Captcha' => Mews\Captcha\Facades\Captcha::class,
]

Once after the setup publish everything,

php artisan vendor:publish

Put the below code in the blade file where the captcha is to be displayed,

<div class="col-lg-6">
<div class="captcha" style="width: 100%;float: left;height: 41px;">
<span class="captcha_span" style="width: 50%;float: left;margin-bottom: 5px;">{!! captcha_img() !!}</span>
<button type="button" class="btn-refresh" style="border: 1px solid transparent;background: transparent;width: 50%;float: left;margin-bottom: 5px;"><i class="la la-refresh" style="color: #3699FF;font-weight: bold;font-size: 30px;"></i></button>
</div>
<input type="text" class="form-control @error('captcha') is-invalid @enderror" name="captcha" id="captcha" placeholder="Enter Captcha">
@error('captcha')
<span class="invalid-feedback" class="width: 50%;float: left;margin-bottom: 5px;" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>

Ajax Captcha Refresh :

Provide the below ajax code in script tag to refresh the captcha in case If you is not able to understand captcha.

$(".btn-refresh").click(function() {
$.ajax({
type: 'GET',
url: '{{ route("refresh_captcha") }}',
success: function(data) {
console.log(data);
$('.captcha_span').html(data.captcha);
}
})
});

Provide the below function in controller,

public function refreshcaptcha(){
return response()->json(['captcha' => captcha_img()]);
}

Add the above function to web.php,

Route::get('refresh_captcha', 'HomeController@refreshcaptcha')->name('refresh_captcha');

Do read this article on laravel CRUD,

Thank you for reading this article.

--

--