A modular security package for Laravel that helps you monitor, detect, and block suspicious or malicious activity in your applications.
Laravel Defender offers advanced request logging, risk pattern detection, brute force and spam protection, and real-time alertsβall fully configurable and privacy-friendly.
Easily integrate Defender into your Laravel projects to enhance your application's security with flexible, modern tools.
βΉοΈ Actively maintained. Feedback and contributions are welcome.
Note:
This package is 100% open source and does not connect to any external service by default.
- π‘οΈ Honeypot-based spam protection for forms
 - ποΈ Request logging and alert system for suspicious activity
 - π View logs and alerts via Artisan command
 - βοΈ Customizable rules and middleware
 - π¨ Advanced risk pattern detection (user-agents, routes, login attempts, country/IP restrictions, path traversal, fuzzing)
 - π Local real-time alerts (log, mail, Slack, webhook)
 - π Security audit command for common Laravel misconfigurations
 
composer require metalinked/laravel-defenderAfter installation, publish the config file:
php artisan vendor:publish --tag=defender-configNote:
Thedatabasechannel is optional, but enabled by default in the alert system.
Only publish and run the migration if you want to keep database logging enabled (see thealerts.channelsoption inconfig/defender.php).
If you disable thedatabasechannel, you do not need to publish or run the migration, and no logs will be stored in the database.
Publish the migration file:
php artisan vendor:publish --tag=defender-migrationsRun the migrations:
php artisan migrateTo ensure Defender can detect and block a wide range of suspicious and malicious access attemptsβincluding requests to non-existent routes (such as /wp-admin, /phpmyadmin, /xmlrpc.php), brute force attacks, access from non-allowed countries, and risky login patterns, you should register all Defender middlewares as global middlewares:
- IpLoggerMiddleware: logs all requests if the 
ip_logging.log_alloption is enabled in the configuration. - AdvancedDetectionMiddleware: detects suspicious user-agents, common attack routes, and login attempts with common usernames.
 - BruteForceMiddleware: detects and blocks brute force attempts from the same IP.
 - CountryAccessMiddleware: allows or denies access based on country or IP whitelist/denylist.
 
Registering these middlewares globally ensures your application is protected against a broad spectrum of attacks, including those targeting non-existent or sensitive routes.
Add the following to your bootstrap/app.php inside the withMiddleware callback:
->withMiddleware(function (Middleware $middleware) {
    $middleware->append(\Metalinked\LaravelDefender\Http\Middleware\AdvancedDetectionMiddleware::class);
    $middleware->append(\Metalinked\LaravelDefender\Http\Middleware\BruteForceMiddleware::class);
    $middleware->append(\Metalinked\LaravelDefender\Http\Middleware\CountryAccessMiddleware::class);
})Add the following to the $middleware array in your app/Http/Kernel.php:
protected $middleware = [
    // ...existing Laravel middleware...
    \Metalinked\LaravelDefender\Http\Middleware\AdvancedDetectionMiddleware::class,
    \Metalinked\LaravelDefender\Http\Middleware\BruteForceMiddleware::class,
    \Metalinked\LaravelDefender\Http\Middleware\CountryAccessMiddleware::class,
];Recommended:
Registering these middlewares globally ensures all requests are protected, including non-existent routes, without needing to add them to individual routes.
This package provides configurable honeypot protection for your Laravel forms.
- 
Publish the Blade view (optional):
php artisan vendor:publish --tag=defender-views
 - 
Add the honeypot field to your forms:
@defenderHoneypot - 
Configure automatic protection (optional): In
config/defender.php, set:'honeypot' => [ 'auto_protect_forms' => true, // or false for manual middleware // ...other options ],
 - 
Manual middleware (if auto protection is disabled): Add the middleware to your route:
Route::post('/your-form', ...)->middleware('defender.honeypot');
 
Laravel Defender can detect and alert on suspicious patterns beyond just IPs.
- Suspicious user-agents: (e.g. curl, python, sqlmap, scanner, etc.)
 - Access to common attack routes: 
/wp-admin,/phpmyadmin,/xmlrpc.php, etc. - Login attempts with common usernames: 
admin,root,test, etc. - Access from blocked or non-allowed countries: (with free IP geolocation)
 - Brute force attempts: Too many requests from the same IP in a short period
 - Path traversal and fuzzing patterns: Attempts to exploit with 
../, encoded traversal, or common fuzzing payloads/tools (e.g. sqlmap, acunetix, etc.) 
In your config/defender.php:
'advanced_detection' => [
    'enabled' => true,
    'geo_provider' => 'ip-api', // 'ip-api', 'ipinfo', 'ipgeolocation'
    'geo_cache_minutes' => 10, // Cache country codes for 10 minutes
    'ipinfo_token' => env('IPINFO_TOKEN'), // API token for ipinfo.io
    'ipgeolocation_key' => env('IPGEOLOCATION_KEY'), // API key for ipgeolocation.io
    'suspicious_user_agents' => [
        'curl', 'python', 'sqlmap', 'nmap', 'nikto', 'fuzzer', 'scanner'
    ],
    'suspicious_routes' => [
        '/wp-admin', '/wp-login', '/phpmyadmin', '/admin.php', '/xmlrpc.php'
    ],
    'common_usernames' => [
        'admin', 'administrator', 'root', 'test', 'user'
    ],
    'country_access' => [
        'mode' => 'allow', // 'allow': only allow these countries, 'deny': block these countries
        'countries' => ['ES'],
        'whitelist_ips' => ['1.2.3.4'], // Always allowed, regardless of country/mode
    ],
],Note:
- You can set 
modeto'allow'(only allow listed countries) or'deny'(block listed countries). - IPs in 
whitelist_ipsare always allowed, regardless of country or mode. - Country detection supports multiple providers:
- ip-api.com (free tier, no registration required, default)
 - ipinfo.io (requires API token for production use)
 - ipgeolocation.io (requires API key)
 
 
Laravel Defender supports local real-time alerts via multiple channels.
log(Laravel log)database(save to the database)mail(send to a configured email)slack(send to a Slack webhook)webhook(send to any external URL)
Only the
loganddatabasechannels are enabled by default.
In your config/defender.php:
'alerts' => [
    'channels' => [
        'log',      // Always enabled by default
        'database', // Enabled to save to the database
        // 'mail',   // Enable to receive email alerts
        // 'slack',  // Enable to receive Slack alerts
        // 'webhook' // Enable to receive alerts via webhook
    ],
    'mail' => [
        'to' => env('DEFENDER_ALERT_MAIL_TO', null),
    ],
    'slack' => [
        'webhook_url' => env('DEFENDER_SLACK_WEBHOOK', null),
    ],
    'webhook' => [
        'url' => env('DEFENDER_ALERT_WEBHOOK', null),
    ],
],You can configure Laravel Defender using the following .env variables:
| Variable | Description | Example | 
|---|---|---|
| DEFENDER_GEO_PROVIDER | Geolocation provider (ip-api, ipinfo, ipgeolocation) | DEFENDER_GEO_PROVIDER=ipinfo | 
| IPINFO_TOKEN | API token for ipinfo.io geolocation service | IPINFO_TOKEN=abcd1234 | 
| IPGEOLOCATION_KEY | API key for ipgeolocation.io service | IPGEOLOCATION_KEY=abcd1234 | 
| DEFENDER_ALERT_MAIL_TO | Email address to receive alert notifications | DEFENDER_ALERT_MAIL_TO=admin@example.com | 
| DEFENDER_SLACK_WEBHOOK | Slack webhook URL for alert notifications | DEFENDER_SLACK_WEBHOOK=https://hooks.slack.com/services/XXX/YYY/ZZZ | 
| DEFENDER_ALERT_WEBHOOK | External webhook URL for alert notifications | DEFENDER_ALERT_WEBHOOK=https://yourdomain.com/defender-webhook | 
All variables are optional and only required if you enable the corresponding alert channel or feature in
config/defender.php.
You can control global request logging and brute force protection in your config/defender.php:
'ip_logging' => [
    'log_all' => false, // WARNING: If true, logs ALL requests (not just suspicious ones).
                        // Only recommended for testing or temporary auditing.
                        // Not suitable for production environments!
],
'brute_force' => [
    'max_attempts' => 5,
    'decay_minutes' => 10,
],ip_logging.log_all: If set totrue, logs every request (not just suspicious ones).
Warning: Only enable this for testing or temporary audits. Not recommended for production!brute_force.max_attempts: Number of allowed attempts before blocking an IP.brute_force.decay_minutes: Time window for counting attempts.
Laravel Defender provides an Artisan command to review access logs and suspicious activity directly from the console.
Important:
Only logs stored in the database (with thedatabasealert channel enabled and migration run) can be viewed or exported using these commands.
Logs written to the Laravel log file (storage/logs/laravel.log) are not accessible via Defender commands.
This approach is secure and convenient, as it does not expose sensitive data via the web and works even if your app does not have a backoffice.
Note:
Viewing and exporting logs is only available if thedatabasechannel is enabled and the migration has been run.
Show the latest 50 logs:
php artisan defender:ip-logsShow only suspicious logs:
php artisan defender:ip-logs --suspiciousFilter by IP:
php artisan defender:ip-logs --ip=1.2.3.4Limit the number of results:
php artisan defender:ip-logs --limit=100You can combine options as needed.
Export all logs to CSV:
php artisan defender:export-logs --format=csvExport only suspicious logs to JSON:
php artisan defender:export-logs --suspicious --format=json --output=suspicious-logs.jsonExport logs for a specific IP and date range:
php artisan defender:export-logs --ip=1.2.3.4 --from=2024-06-01 --to=2024-06-09 --format=csv --output=logs.csvYou can easily clean up old logs from the database (and optionally from Laravel log files) using the built-in Artisan command:
Delete Defender logs older than 90 days from the database:
php artisan defender:prune-logs --days=90Delete Defender logs older than 30 days and also remove old Laravel log files:
php artisan defender:prune-logs --days=30 --laravelNote:
Only logs stored in the database can be listed and exported with Defender commands.
Logs written to the Laravel log file (storage/logs/laravel.log) are not accessible via Defender commands and must be managed manually or with the--laravelprune option.
To automatically prune old Defender logs on a schedule, add the following to your scheduler file:
For Laravel 11 and newer (bootstrap/routes/console.php):
use Illuminate\Support\Facades\Schedule;
Schedule::command('defender:prune-logs --days=90')->daily();For Laravel 10 and earlier (app/Console/Kernel.php):
protected function schedule(Schedule $schedule)
{
    $schedule->command('defender:prune-logs --days=90')->daily();
}This will delete Defender logs older than 90 days every day.
You can adjust the frequency and retention period as needed.
Run a local security audit of your Laravel project:
php artisan defender:auditThis command checks for:
- Publicly accessible 
.envfile - APP_DEBUG enabled
 - Permissive CORS configuration
 - Insecure session cookies
 - Laravel version
 
It gives clear recommendations for each issue found.
Run tests with:
composer testOr if using Pest:
./vendor/bin/pestNote:
Make sure your PHP installation has thesqlite3andpdo_sqliteextensions enabled.
These are required for running the package tests (Testbench uses SQLite in-memory by default).
If you discover a security vulnerability, please report it via email to security@metalinked.net. All reports will be handled responsibly and in confidence.
- Free & Open Source (offline):
All users can use the basic security features locally, without connecting to any external service. No registration required. Privacy-friendly and self-hosted. 
See CONTRIBUTING.md for guidelines on how to contribute.
MIT Β© Metalinked
If you're interested in using this tool or contributing, feel free to open an issue or start a discussion.
π¬ Questions, suggestions or feedback? Join the Discussions!