Ban Users and IPs in Your Laravel App With Banhammer
Published on by Paul Redmond
Banhammer for Laravel offers a simple way to ban any Model by ID and IP; it also allows blocking requests by IP addresses. Once your application bans users, you can use the provided middleware to prevent banned users from accessing certain parts of your application.
Once you install this package, you can quickly ban models via the package's Bannable
trait:
namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable;use Mchev\Banhammer\Traits\Bannable; class User extends Authenticatable{ use Bannable;}
Now, you can ban users with:
$user->ban(); // IP ban$user->ban([ 'ip' => $user->ip,]); // List all bans$model->bans(); // Check ban status$model->isBanned();$model->isNotBanned(); // Unban a model$user->unban();
This package also supports banning IP addresses directly:
use Mchev\Banhammer\IP; IP::ban("8.8.8.8");IP::ban(["8.8.8.8", "4.4.4.4"]);
Another neat feature this package provides is that banned models can have an expiration date. Once a ban expires, the model will be unbanned automatically via the scheduler:
$user->banUntil('2 days');
This package also provides utility methods to clear all bans across the application, including manually unbanning expired bans if you need to clean up expired bans programatically.
You can learn more about this package, get full installation instructions, and view the source code on GitHub.