We recently had the problem that users couldn’t always read the captchas being generated on a client’s site and they wanted a ‘refresh captcha’ option.

The site is built on the fantastic Laravel 5.3 and we’re using the very handy Captcha Service Provider by mewebstudio. Unfortunately according to the readme for this package, it doesn’t appear to have an immediately available option for creating ‘refresh’ functionality, however it’s very easy to accomplish with just a few lines of code which I’ll explain below in case it’s helpful to somebody else out there with the same problem.

1. Clearly you need to install the package as detailed on their Github:
https://github.com/mewebstudio/captcha

2. Once you have implemented the basic captcha in your webform you need to add in an anchor tag for regenerating the image. Our form looks a little something like this (notice the addition of the ‘regen-captcha’ anchor tag):

... etc ...


{!! captcha_img() !!}

Try different captcha

@if ($errors->has('captcha'))
		
				{{ $errors->first('captcha') }}
		
@endif

... etc ...

 

3. Now you need to write a little jQuery (or any other ajax event) to send a request for a new image src. Our jQuery looks like this:

$('#regen-captcha').on('click', function(e){
	e.preventDefault();

	var anchor = $(this);
	var captcha = anchor.prev('img');

	$.ajax({
		type: "GET",
		url: '/ajax_regen_captcha',
	}).done(function( msg ) {
		captcha.attr('src', msg);
	});
});

 

4. You’ll notice this is send a GET request to a specific URL, and setting the response as the src of the preceding image. It’s important therefore, for this code to work, that the ‘regen-captcha’ anchor tag is immediately after the captcha image.

5. Finally you need to setup the Laravel route which will handle the request above, our routes/web.php looks like this:

Route::get('ajax_regen_captcha', function(){
	return captcha_src();
});

 

So there you have it, a very simple way of refreshing the captcha on your form and hopefully make the captcha process a little easier for your users.