Web training courses

Develop your digital skill set


Adding refresh functionality to a Laravel Captcha

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:

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 ...

<input id="captcha" type="captcha" class="form-control captcha" name="captcha" value="{{ old('captcha') }}" required>
{!! captcha_img() !!}

<a href="#" id="regen-captcha">Try different captcha</a>

@if ($errors->has('captcha'))
		<span class="help-block">
				<strong>{{ $errors->first('captcha') }}</strong>

... 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){

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

		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.

by Tom

Tom, Technical Director at 18a, has a degree in Computing and Information Systems and 20 years of commercial coding experience building websites, applications and tools for government departments and businesses all over the world. It was during his third year at university whilst working in industry that he discovered his passion for the web and hasn't looked back since.

Would you like to give your digital knowledge a boost? Join our mailing list.