PHPackages                             metalinked/laravel-defender - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Security](/categories/security)
4. /
5. metalinked/laravel-defender

ActiveLibrary[Security](/categories/security)

metalinked/laravel-defender
===========================

Modular Laravel security: IP logging &amp; alert manager, honeypot spam protection, log/mail/Slack/webhook alerts, security audit, advanced risk detection, export/prune logs, console viewer.

v1.17.2(9mo ago)223↑25%MITPHPPHP ^8.1CI passing

Since Jun 13Pushed 9mo ago1 watchersCompare

[ Source](https://github.com/metalinked/laravel-defender)[ Packagist](https://packagist.org/packages/metalinked/laravel-defender)[ RSS](/packages/metalinked-laravel-defender/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (10)Versions (15)Used By (0)

Laravel Defender
================

[](#laravel-defender)

[![Tests](https://camo.githubusercontent.com/47ffe524d1126eb7f8c2a6c9615063bd28fef72eab7f2fa13d8dd5cbade29932/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d6574616c696e6b65642f6c61726176656c2d646566656e6465722f74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/metalinked/laravel-defender/actions/workflows/tests.yml)[![PHPStan](https://camo.githubusercontent.com/e91d761e62b6ce7d323c09f3bf73730047ebba9d69a98b822164aef3495071e9/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d6574616c696e6b65642f6c61726176656c2d646566656e6465722f7068707374616e2e796d6c3f6272616e63683d6d61696e266c6162656c3d7068707374616e267374796c653d666c61742d737175617265)](https://github.com/metalinked/laravel-defender/actions/workflows/phpstan.yml)[![GitHub Release](https://camo.githubusercontent.com/02cf3c45e8e4ff76986c863602a845258b31cdb6227739fc0d1be300cb0f3003/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f72656c656173652f6d6574616c696e6b65642f6c61726176656c2d646566656e6465723f7374796c653d666c61742d737175617265)](https://github.com/metalinked/laravel-defender/releases)[![Total Downloads](https://camo.githubusercontent.com/1388ec4211187270219a5184fdc13671fe2004b9548f9c3edc0864fca1d7bea7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d6574616c696e6b65642f6c61726176656c2d646566656e6465723f7374796c653d666c61742d737175617265)](https://packagist.org/packages/metalinked/laravel-defender)[![License](https://camo.githubusercontent.com/254988f8f16f43bcaeda47adbf228efe359ca3f0f7557c7d7977e216ff253bb0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6d6574616c696e6b65642f6c61726176656c2d646566656e6465723f7374796c653d666c61742d737175617265)](https://github.com/metalinked/laravel-defender/blob/main/LICENSE.md)

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.

---

✨ Features
----------

[](#-features)

- 🛡️ 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

---

🚀 Installation
--------------

[](#-installation)

```
composer require metalinked/laravel-defender
```

After installation, publish the config file:

```
php artisan vendor:publish --tag=defender-config
```

> **Note:**
> The `database` channel 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 the `alerts.channels` option in `config/defender.php`).
> If you disable the `database` channel, 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-migrations
```

**Run the migrations:**

```
php artisan migrate
```

---

🔒 Global Protection (Recommended)
---------------------------------

[](#-global-protection-recommended)

To 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_all` option 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.

### For Laravel 11 or higher

[](#for-laravel-11-or-higher)

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);
})
```

### For Laravel 10 and earlier

[](#for-laravel-10-and-earlier)

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.

---

🛡️ Honeypot Spam Protection
---------------------------

[](#️-honeypot-spam-protection)

This package provides configurable honeypot protection for your Laravel forms.

### Quick start

[](#quick-start)

1. **Publish the Blade view (optional):**

    ```
    php artisan vendor:publish --tag=defender-views
    ```
2. **Add the honeypot field to your forms:**

    ```
    @defenderHoneypot
    ```
3. **Configure automatic protection (optional):**In `config/defender.php`, set:

    ```
    'honeypot' => [
        'auto_protect_forms' => true, // or false for manual middleware
        // ...other options
    ],
    ```
4. **Manual middleware (if auto protection is disabled):**Add the middleware to your route:

    ```
    Route::post('/your-form', ...)->middleware('defender.honeypot');
    ```

---

🚨 Advanced Risk Pattern Detection
---------------------------------

[](#-advanced-risk-pattern-detection)

Laravel Defender can detect and alert on suspicious patterns beyond just IPs.

### What is detected?

[](#what-is-detected)

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

### How to configure

[](#how-to-configure)

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 `mode` to `'allow'` (only allow listed countries) or `'deny'` (block listed countries).
- IPs in `whitelist_ips` are always allowed, regardless of country or mode.
- Country detection supports multiple providers:
    - [ip-api.com](https://ip-api.com/) (free tier, no registration required, default)
    - [ipinfo.io](https://ipinfo.io/) (requires API token for production use)
    - [ipgeolocation.io](https://ipgeolocation.io/) (requires API key)

---

🔔 Alert System
--------------

[](#-alert-system)

Laravel Defender supports local real-time alerts via multiple channels.

### Supported channels

[](#supported-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 `log` and `database` channels are enabled by default.

### How to configure

[](#how-to-configure-1)

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),
    ],
],
```

---

Environment Variables
---------------------

[](#environment-variables)

You can configure Laravel Defender using the following `.env` variables:

VariableDescriptionExampleDEFENDER\_GEO\_PROVIDERGeolocation provider (ip-api, ipinfo, ipgeolocation)`DEFENDER_GEO_PROVIDER=ipinfo`IPINFO\_TOKENAPI token for ipinfo.io geolocation service`IPINFO_TOKEN=abcd1234`IPGEOLOCATION\_KEYAPI key for ipgeolocation.io service`IPGEOLOCATION_KEY=abcd1234`DEFENDER\_ALERT\_MAIL\_TOEmail address to receive alert notifications`DEFENDER_ALERT_MAIL_TO=admin@example.com`DEFENDER\_SLACK\_WEBHOOKSlack webhook URL for alert notifications`DEFENDER_SLACK_WEBHOOK=https://hooks.slack.com/services/XXX/YYY/ZZZ`DEFENDER\_ALERT\_WEBHOOKExternal 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`.

---

📝 IP Logging &amp; Brute Force Protection
-----------------------------------------

[](#-ip-logging--brute-force-protection)

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 to `true`, 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.

---

📊 Viewing and Exporting IP Logs and Alerts
------------------------------------------

[](#-viewing-and-exporting-ip-logs-and-alerts)

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 the `database` alert 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 the `database` channel is enabled and the migration has been run.

### Usage

[](#usage)

Show the latest 50 logs:

```
php artisan defender:ip-logs
```

Show only suspicious logs:

```
php artisan defender:ip-logs --suspicious
```

Filter by IP:

```
php artisan defender:ip-logs --ip=1.2.3.4
```

Limit the number of results:

```
php artisan defender:ip-logs --limit=100
```

You can combine options as needed.

---

### Export logs to CSV or JSON

[](#export-logs-to-csv-or-json)

Export all logs to CSV:

```
php artisan defender:export-logs --format=csv
```

Export only suspicious logs to JSON:

```
php artisan defender:export-logs --suspicious --format=json --output=suspicious-logs.json
```

Export 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.csv
```

---

🧹 Pruning Old Logs
------------------

[](#-pruning-old-logs)

You 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=90
```

Delete Defender logs older than 30 days and also remove old Laravel log files:

```
php artisan defender:prune-logs --days=30 --laravel
```

> **Note:**
> 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 `--laravel` prune option.

### Scheduled log pruning

[](#scheduled-log-pruning)

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.

---

🔒 Security Audit
----------------

[](#-security-audit)

Run a local security audit of your Laravel project:

```
php artisan defender:audit
```

This command checks for:

- Publicly accessible `.env` file
- APP\_DEBUG enabled
- Permissive CORS configuration
- Insecure session cookies
- Laravel version

It gives clear recommendations for each issue found.

---

🧪 Testing
---------

[](#-testing)

Run tests with:

```
composer test
```

Or if using Pest:

```
./vendor/bin/pest
```

> **Note:**
> Make sure your PHP installation has the `sqlite3` and `pdo_sqlite` extensions enabled.
> These are required for running the package tests (Testbench uses SQLite in-memory by default).

---

🛡️ Security
-----------

[](#️-security)

If you discover a security vulnerability, please report it via email to [security@metalinked.net](mailto:info@metalinked.net). All reports will be handled responsibly and in confidence.

---

Usage Model
-----------

[](#usage-model)

- **Free &amp; 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.

---

🤝 Contributing
--------------

[](#-contributing)

See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on how to contribute.

---

📄 License
---------

[](#-license)

MIT © [Metalinked](https://metalinked.net)

---

📢 Stay in touch
---------------

[](#-stay-in-touch)

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!](https://github.com/metalinked/laravel-defender/discussions)

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance57

Moderate activity, may be stable

Popularity12

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 69% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~4 days

Total

14

Last Release

284d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/a11fd3d2b72b33d9328a563757cff05fa35fd569a0f636ff8138345f62e7478b?d=identicon)[metalinked](/maintainers/metalinked)

---

Top Contributors

[![oskratch](https://avatars.githubusercontent.com/u/16107567?v=4)](https://github.com/oskratch "oskratch (69 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (31 commits)")

---

Tags

alertsbrute-forcecountry-blockingdefendergeoiphoneypotip-logginglaravellogin-protectionmiddlewarephpsecuritymiddlewarelaravelgeoipsecurityalertsHoneypotbrute forcelogin protectiondefenderip-loggingcountry-blocking

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/metalinked-laravel-defender/health.svg)

```
[![Health](https://phpackages.com/badges/metalinked-laravel-defender/health.svg)](https://phpackages.com/packages/metalinked-laravel-defender)
```

###  Alternatives

[jorijn/laravel-security-checker

Added Laravel functionality to the Enlightn Security Checker. Adds a command to check for, and optionally emails you, vulnerabilities when they affect you.

2021.8M1](/packages/jorijn-laravel-security-checker)[tzsk/otp

A secure, database-free One-Time Password (OTP) generator and verifier for PHP and Laravel.

241641.4k1](/packages/tzsk-otp)[dgtlss/warden

A Laravel package that proactively monitors your dependencies for security vulnerabilities by running automated composer audits and sending notifications via webhooks and email

8745.6k](/packages/dgtlss-warden)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
