PHPackages                             eliel-elie/laravel-connection-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. [Database &amp; ORM](/categories/database)
4. /
5. eliel-elie/laravel-connection-guard

ActiveLibrary[Database &amp; ORM](/categories/database)

eliel-elie/laravel-connection-guard
===================================

Project Laravel database connections with configurable guards such as read-only mode, dangerous SQL prevention and custom validation rules.

0.1.1(1mo ago)02↓50%MITPHPPHP ^8.2CI passing

Since Jun 28Pushed 1mo agoCompare

[ Source](https://github.com/eliel-elie/laravel-connection-guard)[ Packagist](https://packagist.org/packages/eliel-elie/laravel-connection-guard)[ RSS](/packages/eliel-elie-laravel-connection-guard/feed)WikiDiscussions main Synced 2w ago

READMEChangelog (2)Dependencies (7)Versions (3)Used By (0)

Laravel Connection Guard
========================

[](#laravel-connection-guard)

[![Latest Version on Packagist](https://camo.githubusercontent.com/6e4bcece5eec39fc691141665e4c02ee9011ba1d15bd99703162d937dd56ad7e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f656c69656c2d656c69652f6c61726176656c2d636f6e6e656374696f6e2d67756172642e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/eliel-elie/laravel-connection-guard)[![Total Downloads](https://camo.githubusercontent.com/506b2992a067f56ea6dd81b2aac76fb11693fcf2e631a1cb8f8f5b5e4c08e816/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f656c69656c2d656c69652f6c61726176656c2d636f6e6e656374696f6e2d67756172642e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/eliel-elie/laravel-connection-guard)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)

**Laravel Connection Guard** is a clean, robust, and elegant package designed to protect your database connections in Laravel. It allows you to intercept SQL queries at runtime and prevent unwanted actions (like writes to read-only replicas, schema updates in production, or accidental UPDATEs/DELETEs without WHERE clauses) before they reach your database.

---

Key Features
------------

[](#key-features)

- **Native Interception**: Uses Laravel's native database connection hooks (`beforeExecuting`), ensuring blocked queries are never executed.
- **Driver-Agnostic**: Works seamlessly with MySQL, PostgreSQL, SQLite, SQL Server, Oracle, and any other Laravel-supported database driver.
- **Built-in Guards &amp; Rules**:
- `read-only`: Blocks all DML writes (`insert`, `update`, `delete`, `merge`, `replace`, `upsert`) and DDL structure modifications.
- `ddl`: Blocks schema changes (DDL: `CREATE`, `DROP`, `ALTER`, `TRUNCATE`, `RENAME`).
- `procedure`: Blocks procedure calls and executions (e.g., `CALL`, `EXECUTE`, `EXEC`).
- `preventive-massive`: Prevents dangerous queries, specifically blocking `UPDATE` and `DELETE` without `WHERE` clauses and `DROP` commands.
- **Flexible Configurations**: Easily exempt specific tables (`except_tables`) or procedures (`except_procedures`) from guards.
- **Runtime Bypass (`withoutGuards`)**: Safely bypass validation for database migrations, seeds, or specific tasks.
- **Extensible**: Easily register custom security rules and guards.

---

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

[](#requirements)

- PHP `^8.2`
- Laravel `^10.0` | `^11.0` | `^12.0` | `^13.0`

---

Installation
------------

[](#installation)

You can install the package via Composer:

```
composer require eliel-elie/laravel-connection-guard
```

Optionally, publish the configuration file:

```
php artisan vendor:publish --tag="connection-guard-config"
```

The published file `config/connection-guard.php` maps convenient aliases to the guard classes:

```
return [
    'guards' => [
        'read-only'          => \Elielelie\ConnectionGuard\Guards\ReadOnlyGuard::class,
        'ddl'                => \Elielelie\ConnectionGuard\Guards\DdlGuard::class,
        'procedure'          => \Elielelie\ConnectionGuard\Guards\ProcedureGuard::class,
        'preventive-massive' => \Elielelie\ConnectionGuard\Guards\PreventiveMassiveGuard::class,
    ],
];
```

---

Usage
-----

[](#usage)

To start protecting your database connections, simply add the `guards` key to your connection configurations in `config/database.php`:

### Example 1: Read-Only Connection (Replica)

[](#example-1-read-only-connection-replica)

```
// config/database.php
'connections' => [
    'mysql_replica' => [
        'driver' => 'mysql',
        'host' => env('DB_REPLICA_HOST', '127.0.0.1'),
        'database' => env('DB_DATABASE', 'forge'),
        // ...
        'guards' => [
            'read-only',
        ],
    ],
],
```

### Example 2: Connection with Exceptions for Specific Tables

[](#example-2-connection-with-exceptions-for-specific-tables)

If your application uses database-driven sessions (`database` session driver) or needs to write to an activity log table on a protected replica, use the array syntax to define exemptions:

```
// config/database.php
'connections' => [
    'mysql_replica' => [
        'driver' => 'mysql',
        // ...
        'guards' => [
            'read-only' => [
                'except_tables' => ['sessions', 'activity_logs', 'migrations'],
            ],
        ],
    ],
],
```

### Example 3: Preventing Massive Updates, Deletes, and Drops

[](#example-3-preventing-massive-updates-deletes-and-drops)

Block massive accidental table updates/deletions lacking filter conditions, and disable `DROP` commands on production connections:

```
// config/database.php
'connections' => [
    'mysql_production' => [
        'driver' => 'mysql',
        // ...
        'guards' => [
            'preventive-massive',
        ],
    ],
],
```

### Example 4: Blocking Structural Schema Changes Only (DDL)

[](#example-4-blocking-structural-schema-changes-only-ddl)

```
// config/database.php
'connections' => [
    'mysql_app' => [
        'driver' => 'mysql',
        // ...
        'guards' => [
            'ddl',
        ],
    ],
],
```

### Example 5: Blocking Procedures with Custom Exemptions

[](#example-5-blocking-procedures-with-custom-exemptions)

Block all stored procedure calls except for specific ones required by your application:

```
// config/database.php
'connections' => [
    'mysql_db' => [
        'driver' => 'mysql',
        // ...
        'guards' => [
            'procedure' => [
                'except_procedures' => ['sp_log_activity', 'sp_get_report'],
            ],
        ],
    ],
],
```

---

Advanced Usage
--------------

[](#advanced-usage)

### Bypassing Guards at Runtime (`withoutGuards`)

[](#bypassing-guards-at-runtime-withoutguards)

If your application needs to execute queries that are normally blocked by guards (e.g., during setup, migrations, or data seeders), wrap the execution in the `withoutGuards` method:

```
use Elielelie\ConnectionGuard\Facades\ConnectionGuard;
use Illuminate\Support\Facades\Schema;

ConnectionGuard::withoutGuards(function () {
    // All guards will be disabled within this closure
    Schema::dropIfExists('old_table');
});
```

You can also toggle the guard state manually:

```
use Elielelie\ConnectionGuard\Facades\ConnectionGuard;

ConnectionGuard::disable();

// Run unprotected operations...

ConnectionGuard::enable();
```

---

Creating Custom Rules and Guards
--------------------------------

[](#creating-custom-rules-and-guards)

You can extend the security system by creating custom rules or registering custom guards:

### Option 1: Creating a Custom SQL Rule (`SqlRule`)

[](#option-1-creating-a-custom-sql-rule-sqlrule)

Create a class that implements `Elielelie\ConnectionGuard\Contracts\SqlRule`:

```
namespace App\Database\Rules;

use Elielelie\ConnectionGuard\Contracts\SqlRule;
use Elielelie\ConnectionGuard\Exceptions\ConnectionGuardException;

class BlockDropDatabaseRule implements SqlRule
{
    public function validate(string $sql): void
    {
        if (str_contains(strtolower($sql), 'drop database')) {
            throw new ConnectionGuardException("Action prohibited: Deleting databases is not allowed!");
        }
    }
}
```

Reference the rule directly in your connection guards:

```
'guards' => [
    \App\Database\Rules\BlockDropDatabaseRule::class,
],
```

### Option 2: Extending the Manager with Custom Guards

[](#option-2-extending-the-manager-with-custom-guards)

Register a custom guard programmatically in the `boot` method of your `AppServiceProvider`:

```
use Elielelie\ConnectionGuard\Facades\ConnectionGuard;
use Elielelie\ConnectionGuard\Contracts\Guard;
use Illuminate\Database\Connection;

ConnectionGuard::extend('custom-audit', function ($app, array $options) {
    return new class implements Guard {
        public function validate(Connection $connection, string $query, array $bindings = []): void
        {
            // Custom validation logic...
        }
    };
});
```

Now, apply it to any connection using its registered alias:

```
'guards' => [
    'custom-audit',
],
```

---

Testing
-------

[](#testing)

To run the Pest test suite:

```
vendor/bin/pest
```

To validate code formatting with Laravel Pint:

```
vendor/bin/pint
```

---

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT License](LICENSE).

###  Health Score

35

—

LowBetter than 77% of packages

Maintenance90

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 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

Every ~0 days

Total

2

Last Release

45d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1af6380064aee246aaface6c2b36f5773e670773e7b7f02df1de33c52dd487f4?d=identicon)[elielelie](/maintainers/elielelie)

---

Top Contributors

[![eliel-elie](https://avatars.githubusercontent.com/u/78655902?v=4)](https://github.com/eliel-elie "eliel-elie (4 commits)")

---

Tags

laraveldatabasemysqlsqlitepostgresqlsqlserveroracleConnectionRead onlyguard

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/eliel-elie-laravel-connection-guard/health.svg)

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

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k8.9M109](/packages/mongodb-laravel-mongodb)[yajra/laravel-oci8

Oracle DB driver for Laravel via OCI8

8723.3M27](/packages/yajra-laravel-oci8)[kirschbaum-development/eloquent-power-joins

The Laravel magic applied to joins.

1.6k35.7M51](/packages/kirschbaum-development-eloquent-power-joins)[psalm/plugin-laravel

Psalm plugin for Laravel

3345.4M354](/packages/psalm-plugin-laravel)[ramadan/custom-fresh

A Laravel package to specify the tables that you do not want to drop while refreshing the database.

611.6k](/packages/ramadan-custom-fresh)[api-platform/laravel

API Platform support for Laravel

58190.1k21](/packages/api-platform-laravel)

PHPackages © 2026

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