PHPackages                             mmeyer2k/laravel-sqli-guard - 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. mmeyer2k/laravel-sqli-guard

ActiveLibrary[Security](/categories/security)

mmeyer2k/laravel-sqli-guard
===========================

SQL injection prevention plugin for laravel

v1.0.0(4w ago)11.7kMITPHPPHP ^8.1CI passing

Since Feb 27Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/mmeyer2k/laravel-sqli-guard)[ Packagist](https://packagist.org/packages/mmeyer2k/laravel-sqli-guard)[ RSS](/packages/mmeyer2k-laravel-sqli-guard/feed)WikiDiscussions master Synced 2d ago

READMEChangelogDependencies (3)Versions (4)Used By (0)

laravel-sqli-guard
==================

[](#laravel-sqli-guard)

A Laravel plugin that forces usage of PDO parameterization and strongly protects against SQL injection attacks.

This package should not be used as a replacement for writing secure queries! [See Caveats](#caveats).

Install
-------

[](#install)

```
composer require mmeyer2k/laravel-sqli-guard
```

The service provider is auto-discovered. No manual registration needed.

Configuration
-------------

[](#configuration)

Publish the config file to customize behavior:

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

This creates `config/sqliguard.php` with the following options:

OptionDefaultDescription`enabled``true`Master switch to enable/disable the guard`log_blocked``true`Log blocked queries at warning level`strict_mode``false`Enable additional patterns (`char(`, `;`) that may cause false positives`extra_needles``[]`Additional patterns to block (strings or regex)`disabled_needles``[]`Built-in patterns to skip if they cause false positivesAll options can be set via environment variables:

```
SQLIGUARD_ENABLED=true
SQLIGUARD_LOG=true
SQLIGUARD_STRICT=false
```

Usage
-----

[](#usage)

This plugin works by checking query strings for unsafe character sequences during the query preparation phase.

The query below will throw an `Illuminate\Database\QueryException` (caused by `SqlInjectionException`) due to the presence of the single quotation mark character in the query string.

```
DB::select("select * from users where id = '$unsafe'");
```

To make this query safe and avoid an exception, use parameterized queries:

```
DB::select("select * from users where id = ?", [$unsafe]);
```

Overriding Protection
---------------------

[](#overriding-protection)

### Scoped (recommended)

[](#scoped-recommended)

Use `withoutProtection()` to temporarily disable the guard. Protection is always restored, even if an exception occurs:

```
use Mmeyer2k\LaravelSqliGuard\SqliGuard;

$result = SqliGuard::withoutProtection(function () {
    return DB::select("select version()");
});
```

### Manual

[](#manual)

```
use Mmeyer2k\LaravelSqliGuard\SqliGuard;

SqliGuard::allowUnsafe();
// Execute queries that would normally be blocked
SqliGuard::blockUnsafe();
```

**Warning:** If an exception is thrown between `allowUnsafe()` and `blockUnsafe()`, protection remains disabled for the rest of the request. Prefer `withoutProtection()` instead.

Forbidden Character Sequences
-----------------------------

[](#forbidden-character-sequences)

### Default patterns (always active)

[](#default-patterns-always-active)

PatternReason`'`The single quotation mark is the most fundamental SQL injection vector.`"`Double quotes can also enable injection in certain contexts.`0x`Hexadecimal literals are used to bypass WAFs looking for quoted sequences.`--`, `#`, `/*`, `*/`Comments can manipulate query logic. Use raw PDO parameters for binary values.`@@`System variable access (`@@version`, `@@datadir`) used for enumeration.`sleep(`Blind timing attacks and connection exhaustion DDoS.`benchmark(`Timing attacks and CPU exhaustion DDoS.`version(`Database version probing to refine attacks.`load_file(`Read arbitrary files from the server filesystem.`into outfile` / `into dumpfile`Write files to the server (webshell deployment).`extractvalue(`XML error-based blind injection in MySQL.`updatexml(`XML error-based blind injection in MySQL.`/\(.*select.*information_schema.*information_schema.*\)/`Blocks DDoS via compound `information_schema` subqueries.### Strict mode patterns (opt-in)

[](#strict-mode-patterns-opt-in)

Enable with `SQLIGUARD_STRICT=true` or `'strict_mode' => true` in config.

PatternReason`char(`Construct strings from character codes to bypass quote filtering.`;`Stacked queries / second-order injection.Events &amp; Logging
--------------------

[](#events--logging)

### Logging

[](#logging)

When `log_blocked` is enabled, blocked queries are logged at the `warning` level with the matched needle and full query string.

### Events

[](#events)

A `Mmeyer2k\LaravelSqliGuard\Events\QueryBlocked` event is dispatched whenever a query is blocked. Listen for it to integrate with your alerting:

```
use Mmeyer2k\LaravelSqliGuard\Events\QueryBlocked;

Event::listen(QueryBlocked::class, function (QueryBlocked $event) {
    // $event->needle — the pattern that matched
    // $event->query  — the full query string
    // Send to Slack, PagerDuty, etc.
});
```

### Exception handling

[](#exception-handling)

Blocked queries throw `Mmeyer2k\LaravelSqliGuard\SqlInjectionException` (wrapped in Laravel's `QueryException`). You can catch it specifically:

```
use Mmeyer2k\LaravelSqliGuard\SqlInjectionException;

try {
    DB::select($query);
} catch (\Illuminate\Database\QueryException $e) {
    if ($e->getPrevious() instanceof SqlInjectionException) {
        // Handle SQL injection attempt
    }
}
```

Laravel Octane Support
----------------------

[](#laravel-octane-support)

The guard automatically resets its state between Octane requests, preventing state leakage across long-lived workers. No additional configuration is needed.

Query Normalization
-------------------

[](#query-normalization)

Queries are normalized before inspection to prevent evasion:

- Null bytes are stripped (`\0`)
- Converted to lowercase
- Whitespace is collapsed
- Spaces before parentheses are removed

Caveats
-------

[](#caveats)

Unfortunately, not all SQL injection scenarios can be blocked by this inspection.

Queries that blindly accept user input can still be manipulated to subvert your application, leak data, or cause denial of service.

A query that returns data can be manipulated to leak records. Consider this poorly written hypothetical API controller route:

```
function users()
{
    $id = request('id');

    return json_encode(DB::select("select * from users where id = $id"));
}
```

If the query string `?id=1 or id > 1` is given, all records will be returned. Depending on the context, this could be a major security issue.

Another concern is that some DDoS attacks are possible if the attacker knows, or can guess, information about the data schema. Again using the above function as an example, but now the query string `id= (SELECT COUNT(*) FROM users A, users B, users C, ...)` is sent. CPU exhaustion can occur if there are many rows in the specified table(s), or if the number of junctions is high. A similar attack is possible against `information_schema`, but it requires **no knowledge**.

Requirements
------------

[](#requirements)

- PHP 8.1+
- Laravel 9.x, 10.x, 11.x, or 12.x

###  Health Score

44

—

FairBetter than 92% of packages

Maintenance89

Actively maintained with recent releases

Popularity23

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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

Unknown

Total

1

Last Release

28d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4c39fe5f8d80dda8a5735401c12cb631d5e17050f7baa7cd3f0f384167fb45db?d=identicon)[mmeyer2k](/maintainers/mmeyer2k)

---

Top Contributors

[![mmeyer2k](https://avatars.githubusercontent.com/u/1887431?v=4)](https://github.com/mmeyer2k "mmeyer2k (23 commits)")

---

Tags

laravelsecuritySQL Injectionsqliwaf

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mmeyer2k-laravel-sqli-guard/health.svg)

```
[![Health](https://phpackages.com/badges/mmeyer2k-laravel-sqli-guard/health.svg)](https://phpackages.com/packages/mmeyer2k-laravel-sqli-guard)
```

###  Alternatives

[akaunting/laravel-firewall

Web Application Firewall (WAF) package for Laravel

999465.8k2](/packages/akaunting-laravel-firewall)[enlightn/laravel-security-checker

A Laravel package to scan your dependencies for known security vulnerabilities.

51173.4k](/packages/enlightn-laravel-security-checker)[glaivepro/hidevara

Laravel millipackage that hides variables from getting dumped in the Whoops page when your app crashes.

27303.9k](/packages/glaivepro-hidevara)

PHPackages © 2026

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