PHPackages                             mamun724682/laravel-db-governor - 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. mamun724682/laravel-db-governor

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

mamun724682/laravel-db-governor
===============================

Safe production database access for Laravel with query approvals, audit logs, and rollback.

v0.1.0(3mo ago)01MITPHPPHP ^8.1

Since Apr 24Pushed 2mo agoCompare

[ Source](https://github.com/mamun724682/laravel-db-governor)[ Packagist](https://packagist.org/packages/mamun724682/laravel-db-governor)[ Docs](https://github.com/mamun724682/laravel-db-governor)[ RSS](/packages/mamun724682-laravel-db-governor/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependencies (10)Versions (2)Used By (0)

Laravel DB Governor
===================

[](#laravel-db-governor)

[![Latest Version on Packagist](https://camo.githubusercontent.com/4130eba6ea81ba2198731d382defffb017fc6d82cabc932eb7fa5e597c432571/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d616d756e3732343638322f6c61726176656c2d64622d676f7665726e6f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mamun724682/laravel-db-governor)[![Total Downloads](https://camo.githubusercontent.com/502a71ad9df66be9381c28af272e400a549ecac4049895c121e522c8b4e2d2dc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d616d756e3732343638322f6c61726176656c2d64622d676f7665726e6f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mamun724682/laravel-db-governor)[![GitHub Stars](https://camo.githubusercontent.com/73199707702e84a42e350d71c7d2f1ef71dab4d8d1bfcf8e92dcb435e2addcd6/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f6d616d756e3732343638322f6c61726176656c2d64622d676f7665726e6f723f7374796c653d666c61742d737175617265)](https://github.com/mamun724682/laravel-db-governor/stargazers)[![PHP](https://camo.githubusercontent.com/074222e0a3638b5a49cfb83132a87bf74c33c88485955358673cd65d9b754036/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312532422d626c75653f7374796c653d666c61742d737175617265)](https://php.net)[![Laravel](https://camo.githubusercontent.com/83709ba9cfd79cb6e204c79252d48d1875a40e69f41bdd7ca0232fdb845f7390/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d313025323025453225383025393325323031332d7265643f7374796c653d666c61742d737175617265)](https://laravel.com)[![License](https://camo.githubusercontent.com/82157ebbf3c9370dfef1e937774f595157a51f3d3014302e7234697a7109d740/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6d616d756e3732343638322f6c61726176656c2d64622d676f7665726e6f722e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Tests](https://camo.githubusercontent.com/84e165cff4596f841c6cb24da2618217bdc59c829b54e04274da849eff61a1c0/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d706573742d677265656e3f7374796c653d666c61742d737175617265)](https://pestphp.com)

**A production-safety database governance layer for Laravel teams.**Intercept, review, approve, execute, and roll back SQL queries through a secure web UI — with full audit trails, risk scoring, and row-level snapshots.

---

Why DB Governor?
----------------

[](#why-db-governor)

Running raw `UPDATE` or `DELETE` queries directly on a production database is dangerous. One wrong `WHERE` clause (or no clause at all) can silently wipe data. **DB Governor** forces every write query through a structured approval workflow before it ever touches your database.

- ✅ Employees submit queries → Admins review &amp; approve → Execution is controlled
- ✅ Every query is scored for risk and flagged for dangerous patterns
- ✅ Before execution, row-level snapshots are captured for instant rollback
- ✅ Full audit log with submitter, reviewer, executor identity and timestamps
- ✅ Works across **multiple database connections** from a single UI

---

Features
--------

[](#features)

### 🔐 Role-Based Access

[](#-role-based-access)

Two roles configured entirely via environment variables — no extra tables required.

RoleCapabilities**Admin**Approve / Reject / Execute / Rollback, view all queries from all users**Employee**Submit queries, view own submissions; SELECTs execute immediatelyToken-based sessions (stored in cache) with configurable expiry (`DB_GOVERNOR_TOKEN_EXPIRY`). Role is re-derived on every request so promotions/demotions take effect without re-login.

---

### 📋 Query Approval Workflow

[](#-query-approval-workflow)

```
Submit → [pending] → Approve → [approved] → Execute → [executed]
                   ↘ Reject → [rejected]            ↘ Rollback → [rolled_back]

```

Every query record stores:

- Raw SQL, query type (READ / WRITE / DDL), affected table
- Submitter email + IP, submission timestamp
- Reviewer email, review timestamp, review note
- Executor email, execution timestamp, rows affected, execution time (ms)
- Execution error (if any) — surfaced immediately in the UI

---

### ⚠️ Automatic Risk Scoring

[](#️-automatic-risk-scoring)

Every submitted query is analysed before it enters the queue:

Risk LevelTrigger`critical`Matches a **blocked pattern** (e.g. `DROP TABLE`, `TRUNCATE`) — query is blocked outright`high`Matches a **flagged pattern** (e.g. `UPDATE … SET` without `WHERE`) or estimated rows exceed `max_affected_rows``medium` / `low`Everything elseBlocked/flagged patterns are fully customisable regex arrays in the config. A dry-run engine estimates affected row counts before submission.

---

### ↩️ Row-Level Rollback

[](#️-row-level-rollback)

Before executing any `UPDATE` or `DELETE`, DB Governor captures a **before-state snapshot** of every affected row. If something goes wrong after execution, a one-click Rollback:

- Re-inserts deleted rows (via `INSERT`)
- Restores updated columns to their original values (via `UPDATE … WHERE pk = ?`)
- Wraps everything in a single database transaction

Snapshots are stored as JSON in the audit record. Configurable via `snapshot_max_rows` (default: 500 rows).

---

### 🖥️ SQL Console

[](#️-sql-console)

A full in-browser SQL console with two modes:

**Query Builder** (visual, no SQL knowledge needed)

- `SELECT` — pick columns, add WHERE / ORDER BY / LIMIT
- `INSERT` — all non-`id` columns pre-filled; required fields (NOT NULL, no default) are marked with `*` and locked
- `UPDATE` — add/remove SET columns with WHERE condition
- `DELETE` — WHERE condition with danger warning

**Raw SQL** — free-form textarea with:

- SQL keyword + table + column autocomplete
- Arrow-key navigation through suggestions

Value inputs adapt to column type automatically:

- `date` / `datetime` / `timestamp` → native date/time pickers
- `json` → resizable monospace textarea
- Everything else → plain text input

---

### 📊 Table Browser

[](#-table-browser)

Browse any table directly in the UI:

- Paginated rows (25 per page), sortable column headers
- Advanced filter builder with AND / OR groups and operators (`=`, `!=`, `LIKE`, `NOT LIKE`, `>`, `=`, ` [
    'main'    => 'mysql',
    'replica' => 'mysql_read',
    'legacy'  => 'pgsql',
],
```

Switch between connections from the UI. Each connection has its own table browser, query log, and SQL console.

---

### 🛡️ Hidden Tables

[](#️-hidden-tables)

Framework-internal tables (`migrations`, `cache`, `sessions`, `jobs`, `telescope_*`, etc.) are hidden from the UI by default and blocked from query execution.

---

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

[](#requirements)

RequirementVersionPHP`^8.1`Laravel`^10 | ^11 | ^12 | ^13`DatabaseMySQL, PostgreSQL, SQLite---

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

[](#installation)

```
composer require mamun724682/laravel-db-governor
```

Publish the config and run migrations:

```
php artisan vendor:publish --tag=db-governor-config
php artisan migrate
```

Optionally publish views to customise the UI:

```
php artisan vendor:publish --tag=db-governor-views
```

---

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

[](#configuration)

Add to your `.env`:

```
# Who can access the UI
DB_GOVERNOR_ADMINS=admin@company.com,dba@company.com
DB_GOVERNOR_EMPLOYEES=dev1@company.com,dev2@company.com

# Which Laravel DB connection to govern
DB_GOVERNOR_CONNECTION_KEY=main
DB_GOVERNOR_CONNECTION=mysql

# Optional tweaks
DB_GOVERNOR_PATH=db-governor          # URL prefix
DB_GOVERNOR_TOKEN_EXPIRY=8            # session hours
DB_GOVERNOR_MAX_ROWS=1000             # high-risk row threshold
DB_GOVERNOR_DRY_RUN=true              # enable row estimation
DB_GOVERNOR_SNAPSHOT_MAX=500          # max rows to snapshot
DB_GOVERNOR_SCHEMA_CACHE_TTL=300      # schema cache in seconds (0 = off)
DB_GOVERNOR_LOG_READS=true            # log SELECT queries for audit
DB_GOVERNOR_STORAGE_CONNECTION=null   # separate DB for the governance table
```

Full config reference at `config/db-governor.php` after publishing.

---

Usage
-----

[](#usage)

Navigate to `http://your-app.test/db-governor` and log in with an admin or employee email.

### Workflow example

[](#workflow-example)

```
1. Employee logs in → opens SQL Console → builds INSERT query visually
2. Clicks "Generate SQL →" → reviews raw SQL → submits with a description
3. Admin logs in → sees pending query in Query Log → reviews SQL and risk flags
4. Admin approves with a note → clicks Execute → rows affected shown immediately
5. Something went wrong? → Admin clicks Rollback → rows restored from snapshot

```

---

Customising Risk Patterns
-------------------------

[](#customising-risk-patterns)

```
// config/db-governor.php

// Block outright (status = blocked, never queued)
'blocked_patterns' => [
    '/^\s*DROP\s+(TABLE|DATABASE|SCHEMA)/i',
    '/^\s*TRUNCATE\s+/i',
],

// Flag as high risk (queued but prominently warned)
'flagged_patterns' => [
    '/UPDATE\s+\w[\w.]*\s+SET(?!.*\bWHERE\b)/is',  // UPDATE without WHERE
    '/DELETE\s+FROM\s+\w[\w.]*\s*(?!WHERE)/is',      // DELETE without WHERE
],
```

---

Multiple Connections
--------------------

[](#multiple-connections)

```
'connections' => [
    'prod'    => env('DB_PROD_CONNECTION', 'mysql'),
    'staging' => env('DB_STAGING_CONNECTION', 'mysql_staging'),
    'legacy'  => 'pgsql_legacy',
],
```

Each connection gets its own URL: `/db-governor/prod`, `/db-governor/staging`, etc.

---

Security
--------

[](#security)

- Login issues a random 32-character token; the token string is stored in the Laravel session, the payload (email, role, expiry) is stored in the **cache** — no auth table or users table required
- Token expiry is configurable; tokens are invalidated immediately on logout
- Role is re-checked on every request — revoking access in config takes immediate effect without re-login
- Login is rate-limited to **5 attempts per minute per IP**; the counter clears on successful login
- All write query execution is gated behind the approval workflow
- Blocked patterns are matched **after stripping SQL comments** to prevent `/* bypass */` evasion
- Hidden tables are enforced both in the UI and at the query execution layer

---

Development
-----------

[](#development)

```
# Install dependencies
composer install

# Run tests
composer test

# Run tests with coverage
composer test:coverage

# Check code style
composer lint

# Fix code style
composer lint:fix
```

---

Contributing
------------

[](#contributing)

Pull requests are welcome. Please open an issue first to discuss significant changes.

1. Fork the repository
2. Create a feature branch (`git checkout -b feat/my-feature`)
3. Write tests for your changes
4. Ensure `composer test` and `composer lint` both pass
5. Submit a pull request

---

Support
-------

[](#support)

If DB Governor helps your team, please star the repository.

---

License
-------

[](#license)

The MIT License (MIT). See [LICENSE](LICENSE) for details.

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance84

Actively maintained with recent releases

Popularity1

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity32

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

Unknown

Total

1

Last Release

91d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/6facc4c6625466cee20f2c66a51be644673cf4d8df01f5a7bb3bc2b9cd6dc566?d=identicon)[mamun167359](/maintainers/mamun167359)

---

Top Contributors

[![mamun724682](https://avatars.githubusercontent.com/u/41566116?v=4)](https://github.com/mamun724682 "mamun724682 (109 commits)")

---

Tags

laraveldatabasesqlproductionaudit-logrollbackquery-monitoringquery-approvaldb-accessgovernor

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/mamun724682-laravel-db-governor/health.svg)

```
[![Health](https://phpackages.com/badges/mamun724682-laravel-db-governor/health.svg)](https://phpackages.com/packages/mamun724682-laravel-db-governor)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.3M347](/packages/psalm-plugin-laravel)[laravel/cashier

Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services.

2.5k30.2M151](/packages/laravel-cashier)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

45444.2k1](/packages/pressbooks-pressbooks)[api-platform/laravel

API Platform support for Laravel

58174.6k17](/packages/api-platform-laravel)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9762.4M133](/packages/roots-acorn)[yajra/laravel-oci8

Oracle DB driver for Laravel via OCI8

8793.2M25](/packages/yajra-laravel-oci8)

PHPackages © 2026

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