PHPackages                             sowailem/fieldguard - 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. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. sowailem/fieldguard

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

sowailem/fieldguard
===================

FieldGuard is a Laravel package that enforces field-level security on Eloquent models, allowing fine-grained control over who can view or modify specific attributes—perfect for role-based data protection without altering your core models.

1.0.3(3mo ago)34102MITPHPPHP ^8.3CI passing

Since Jan 27Pushed 3mo agoCompare

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

READMEChangelog (1)Dependencies (6)Versions (6)Used By (0)

FieldGuard
==========

[](#fieldguard)

[![FieldGuard](images/infograph-fieldguard.png)](images/infograph-fieldguard.png)

FieldGuard is a lightweight, non-intrusive Laravel package for field-level security on Eloquent models. It allows you to control which users can view or modify specific attributes using dynamic, database-driven rules.

[![YouTube Video](https://raw.githubusercontent.com/sowailem/FieldGuard/refs/heads/main/images/fieldguard-hero.png)](https://www.youtube.com/watch?v=vbixycjWKHo)

Features
--------

[](#features)

- **Database-Driven Rules**: Create and manage security rules in the database for runtime configuration.
- **Non-Intrusive**: No traits, base classes, or attributes required for your models.
- **Automatic Enforcement**: Optionally enforce security via model events (`retrieved`, `saving`) without any code changes.
- **Read &amp; Write Protection**: Separate rules for viewing and updating fields.
- **Data Masking**: Automatically mask sensitive fields (e.g., `***-***-***`).
- **Middleware Integration**: Automatically filter unauthorized fields from incoming requests.
- **Caching**: Performance-optimized with Laravel cache support for database rules.
- **No-Code Friendly**: Centralized control without altering your core models.

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

[](#installation)

```
composer require sowailem/fieldguard
```

Run the migrations to create the rules table:

```
php artisan migrate
```

Usage
-----

[](#usage)

### 1. Creating Security Rules

[](#1-creating-security-rules)

All field-level permissions are managed through the `field_guard_rules` table. You can use the `FieldGuardRule` model to create rules.

```
use Sowailem\FieldGuard\Models\FieldGuardRule;

FieldGuardRule::create([
    'model_class' => 'App\Models\User',
    'field_name' => 'salary',
    'read_policy' => ['roles' => ['admin', 'hr'], 'allow_self' => true],
    'write_policy' => ['roles' => ['admin']],
    'mask' => 'PROTECTED',
    'is_active' => true,
]);
```

#### Rule Structure

[](#rule-structure)

- `model_class`: Fully qualified class name of the Eloquent model.
- `field_name`: The name of the attribute to secure.
- `read_policy`: (Optional) Permission for viewing the field. Can be a string or JSON object.
- `write_policy`: (Optional) Permission for creating or updating the field. Can be a string or JSON object.
- `mask`: (Optional) Value to return if `read` permission is denied (instead of removing the field).
- `is_active`: Boolean to enable/disable the rule (defaults to true).

#### Policy Types

[](#policy-types)

Policies can be:

- `Gate Name`: A Laravel Gate name (e.g., `'view-salary'`).
- `'self'`: Allows access if the user's ID matches the model's primary key.
- `'role:name'`: Requires the user to have a specific role (expects a `hasRole($role)` method on the User model).
- `'true'` / `'false'`: Always allow or always deny.
- `JSON Array`: For complex logic (e.g., `['roles' => ['admin'], 'allow_self' => true, 'gate' => 'extra-check']`).

### 2. Enforcing Security

[](#2-enforcing-security)

#### Automatic Enforcement (Global)

[](#automatic-enforcement-global)

You can enable automatic enforcement for all models by setting `automatic_enforcement` to `true` in your `config/fieldguard.php`. This uses Eloquent events to filter fields automatically.

```
'automatic_enforcement' => true,
```

- **Read**: Automatically hides or masks fields when a model is retrieved from the database.
- **Write**: Automatically prevents unauthorized fields from being saved (reverts to original values).

#### Manual Enforcement (Read)

[](#manual-enforcement-read)

Use the `FieldGuard` facade to filter model attributes. This is useful in controllers or API resources.

```
use Sowailem\FieldGuard\Facades\FieldGuard;

public function view(User $user)
{
    // Returns the model attributes as an array, filtered by security rules
    return FieldGuard::apply($user, auth()->user());
}
```

#### API Resource Integration

[](#api-resource-integration)

```
public function toArray($request)
{
    return FieldGuard::apply($this->resource, $request->user());
}
```

#### Automatic Enforcement (Middleware - Write)

[](#automatic-enforcement-middleware---write)

Register the middleware in your `bootstrap/app.php` (Laravel 11+) or `app/Http/Kernel.php`:

```
// Laravel 11+ example in bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'fieldguard' => \Sowailem\FieldGuard\Middleware\EnforceFieldSecurityMiddleware::class,
    ]);
})
```

Apply it to routes to filter request data before it reaches your controller:

```
Route::put('/users/{user}', [UserController::class, 'update'])
    ->middleware('fieldguard:App\Models\User');
```

The middleware will automatically remove unauthorized fields from `$request->all()` before they reach your controller logic.

### 3. Caching

[](#3-caching)

Database rules are cached for performance. By default, they are cached using the tag `fieldguard:rules` (configurable in `config/fieldguard.php`). When you update rules via the provided `FieldGuardRuleRepository`, the cache is automatically cleared.

You can also manually clear the cache:

```
php artisan fieldguard:clear-cache
```

### 4. Custom Policy Resolvers

[](#4-custom-policy-resolvers)

If you need custom logic for interpreting database policies (e.g., integrating with a specific RBAC system), implement the `PolicyResolver` interface and register it in `config/fieldguard.php`.

```
namespace App\Security;

use Sowailem\FieldGuard\Contracts\PolicyResolver;
use Illuminate\Database\Eloquent\Model;

class MyCustomResolver implements PolicyResolver
{
    public function resolve(array $policy, Model $model, $user): bool
    {
        // Your custom logic here
        return true;
    }
}
```

Register it in `config/fieldguard.php`:

```
'resolver' => \App\Security\MyCustomResolver::class,
```

### 5. Seeding Initial Rules

[](#5-seeding-initial-rules)

The package includes a seeder example to help you bootstrap rules. You can publish and run the seeder or use the provided example:

```
php artisan db:seed --class="Sowailem\FieldGuard\Database\Seeders\FieldGuardRuleSeeder"
```

### 6. Administrative API

[](#6-administrative-api)

FieldGuard comes with built-in RESTful API endpoints for managing security rules.

- `GET /field-guard/rules` – List all rules (supports pagination and filtering)
- `POST /field-guard/rules` – Create a new rule
- `GET /field-guard/rules/{id}` – View a specific rule
- `PUT/PATCH /field-guard/rules/{id}` – Update an existing rule
- `DELETE /field-guard/rules/{id}` – Delete a rule

#### Configuration

[](#configuration)

You can customize the API prefix and middleware in `config/fieldguard.php`:

```
'api' => [
    'enabled' => true,
    'prefix' => 'field-guard',
    'middleware' => ['api', 'auth:sanctum'],
],
```

#### Authorization

[](#authorization)

The API uses a gate named `manage-field-guard` to authorize requests. Ensure you define this gate in your `AuthServiceProvider` or `AppServiceProvider`:

```
use Illuminate\Support\Facades\Gate;

Gate::define('manage-field-guard', function ($user) {
    return $user->isAdmin(); // Your authorization logic
});
```

#### Publishing Routes

[](#publishing-routes)

If you want to customize the routes, you can publish them:

```
php artisan vendor:publish --tag="fieldguard-routes"
```

Then disable the automatic loading in `config/fieldguard.php` and manually register them in your `routes/api.php`.

Testing
-------

[](#testing)

```
vendor/bin/phpunit
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance80

Actively maintained with recent releases

Popularity16

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

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

4

Last Release

105d ago

### Community

Maintainers

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

---

Top Contributors

[![sowailem](https://avatars.githubusercontent.com/u/6251878?v=4)](https://github.com/sowailem "sowailem (16 commits)")[![emadrashad](https://avatars.githubusercontent.com/u/16463475?v=4)](https://github.com/emadrashad "emadrashad (2 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/sowailem-fieldguard/health.svg)

```
[![Health](https://phpackages.com/badges/sowailem-fieldguard/health.svg)](https://phpackages.com/packages/sowailem-fieldguard)
```

###  Alternatives

[tymon/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

11.5k49.1M350](/packages/tymon-jwt-auth)[bezhansalleh/filament-shield

Filament support for `spatie/laravel-permission`.

2.8k2.9M88](/packages/bezhansalleh-filament-shield)[php-open-source-saver/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

8359.8M53](/packages/php-open-source-saver-jwt-auth)[illuminate/auth

The Illuminate Auth package.

9327.3M1.0k](/packages/illuminate-auth)[andrewdwallo/filament-companies

A comprehensive Laravel authentication and authorization system designed for Filament, focusing on multi-tenant company management.

34450.0k2](/packages/andrewdwallo-filament-companies)[alajusticia/laravel-logins

Session management in Laravel apps, user notifications on new access, support for multiple separate remember tokens, IP geolocation, User-Agent parser

2011.0k](/packages/alajusticia-laravel-logins)

PHPackages © 2026

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