Adding refresh functionality to a Laravel Captcha

1st Feb 2017
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.

Leave a Comment

Submitting this form will create you an account on this site for submitting comments, raising disputes and other features as we add them. If you've already got an account you will receive an email asking you to confirm this comment is really by you!

Know a great web designer, developer or marketer?

Tell them to apply to join The Web Guild - it’s free for anyone who gets a company profile approved before the end of March! Read our How it Works page or sign up here!

<< Back to news