★ Preventing spam submitted through forms

Written by murze.be - - Aggregated on Monday January 7, 2019

When adding a form to a public site, there's a risk that spam bots will try to submit it with fake values. We recently released a new package, called laravel-honeypot, that can detect these spammy requests.

How honeypots work #

The majority of spam bots are pretty dumb. You can thwart most of them by adding an invisible field to your form that should never contain a value when submitted. Such a field is called a honeypot. These spam bots will fill all fields, including the honeypot. When a submission comes in with a filled honeypot field, our package will discard that request.

Using the package #

Using it is easy. First, you must add the @honeypot blade directive to any form you wish to protect.

<form method="POST" action="{{ action(App\Http\Controllers\ContactFormSubmissionController::class, 'create') }}")>
    @honeypot
    <input name="myField" type="text">
</form>

@honeypot will add two fields: my_name and my_time (you can change the names in the config file).

Next, you must use the Spatie\Honeypot\ProtectAgainstSpam middleware in the route that handles the form submission. This middleware will intercept any request that submits a non-empty value for the key named my_name.

Most humans need a bit of time to fill out a form. The other field added by the Blade directive, my_time, is used to detect if the form was submitted faster than a second.

use App\Http\Controllers\ContactFormSubmissionController;
use Spatie\Honeypot\ProtectAgainstSpam;

Route::post([ContactFormSubmissionController::class, 'create'])->middleware(ProtectAgainstSpam::class);

If your app has a lot of forms handled by many different controllers, you could opt to register it as global middleware.

// inside app\Http\Kernel.php

protected $middleware = [
   // ...
   \Spatie\Honeypot\ProtectAgainstSpam::class,
];

In closing #

A honeypot is an excellent first line of defense against spam. In my projects, it could prevent most cases of spam submission. Though a honeypot easily fools most bots, there are smarter bots around too that after a while can detect the honeypot fields. In that case, a Google Recaptcha or using a service like Akismet can be a good second line of defense.

If you like laravel-honeypot, be sure to check out the other packages team Spatie has released previously.


« Make it last - Cal Evans

Scotch.io - 6 Popular CSS Frameworks to Use in 2019 »