PHPackages                             euacreations/laravel-iam - 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. euacreations/laravel-iam

ActiveLibrary

euacreations/laravel-iam
========================

IAM / RBAC package for Laravel

v1.0.3(3mo ago)05MITPHPPHP ^8.2

Since Feb 3Pushed 3mo agoCompare

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

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

Laravel IAM
===========

[](#laravel-iam)

[![License: MIT](https://camo.githubusercontent.com/08cef40a9105b6526ca22088bc514fbfdbc9aac1ddbf8d4e6c750e3a88a44dca/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d626c75652e737667)](LICENSE)[![PHP Version](https://camo.githubusercontent.com/d0f9a5e13a3919683bb7b5c1fb30352c20894979febee599b5246b34b8944f0a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344382e312d627269676874677265656e)](https://www.php.net/)[![Laravel Version](https://camo.githubusercontent.com/a9300743b16595f9c181d03fc9a9304a20c2e964059b6f1a503170ea7c4d0a92/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d25354531322e302d6f72616e6765)](https://laravel.com/)

> **Feature-based Identity &amp; Access Management for Laravel**

---

Overview
--------

[](#overview)

Laravel IAM is a feature-first, action-driven authorization system for Laravel. It focuses on **capabilities** (Features) instead of arbitrary permission labels, ensuring that system capabilities are always in sync with your codebase.

### Key Principles

[](#key-principles)

- Users have exactly one role
- Features correspond to actual system actions (controllers/routes)
- Admin role automatically has all features
- Automatic sync for new features added to the system

---

Core Concepts
-------------

[](#core-concepts)

ConceptDescription**Feature**A concrete system action, e.g., `subscriber.create`**Role**A bundle of features assigned to a user**User**A single identity that authenticates using username (email optional)**Admin**Built-in user with all features and root privileges---

Features
--------

[](#features)

- ✅ Feature-based authorization (action-driven)
- ✅ Username-first authentication
- ✅ Single role per user
- ✅ Automatic feature discovery from routes
- ✅ Automatic feature assignment to Admin and roles with auto-assign enabled
- ✅ Laravel Gate &amp; Blade integration
- ✅ Framework-agnostic, no UI
- ✅ Multi-provider authentication support (local, OAuth)

---

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

[](#installation)

Install via Composer:

```
composer require euacreations/laravel-iam
```

Publish config (optional):

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

Run migrations:

```
php artisan migrate
```

---

Minimal Installation Requirements
---------------------------------

[](#minimal-installation-requirements)

Before running `iam:install`, ensure:

1. At least one user exists in your application.
    - You can verify with: ```
        php artisan iam:user-list
        ```
2. Your `users` table has a `role_id` column.
3. Your `User` model uses the IAM trait.

If no users exist, `iam:install` will stop and ask you to create the first user.

Add `role_id` to Users
----------------------

[](#add-role_id-to-users)

Create a migration to add the `role_id` column:

```
Schema::table('users', function (Blueprint $table) {
    $table->foreignId('role_id')->nullable()->constrained('iam_roles');
});
```

Add IAM Trait to User
---------------------

[](#add-iam-trait-to-user)

```
use EuaCreations\LaravelIam\Traits\HasFeatures;

class User extends Authenticatable
{
    use HasFeatures;

    public function role()
    {
        return $this->belongsTo(\EuaCreations\LaravelIam\Models\Role::class);
    }
}
```

---

Quick Start
-----------

[](#quick-start)

### 1. Define Features in Routes

[](#1-define-features-in-routes)

Features are automatically defined from routes using middleware. When you use `feature` without a parameter, the **route name becomes the feature slug**.

```
Route::post('/subscriber', [SubscriberController::class, 'store'])
    ->name('subscriber.create')
    ->middleware('feature');

Route::delete('/subscriber/{id}', [SubscriberController::class, 'destroy'])
    ->name('subscriber.delete')
    ->middleware('feature');
```

You can still pass an explicit slug:

```
Route::post('/subscriber', [SubscriberController::class, 'store'])
    ->middleware('feature:subscriber.create');
```

### 2. Sync Features

[](#2-sync-features)

Run the Artisan command to discover and register features:

```
php artisan iam:sync-features
```

This will:

- Register missing features from your routes
- Automatically assign them to Admin
- Assign to roles with `auto_assign_new_features = true`

### 3. Create Roles and Assign Features

[](#3-create-roles-and-assign-features)

```
use EuaCreations\LaravelIam\Models\Role;
use EuaCreations\LaravelIam\Models\Feature;

// Create a role
$role = Role::create([
    'name' => 'Content Manager',
    'auto_assign_new_features' => false
]);

// Assign specific features to role
$createFeature = Feature::where('slug', 'subscriber.create')->first();
$role->features()->attach($createFeature);

// Assign user to role
$user->update(['role_id' => $role->id]);
```

### 4. Check Authorization

[](#4-check-authorization)

Use Laravel's native authorization methods:

```
// In controllers
if (Gate::allows('subscriber.delete')) {
    // User can delete subscribers
}

// In Blade templates
@can('subscriber.create')
    Create Subscriber
@endcan

// Using middleware
Route::delete('/subscriber/{id}', [SubscriberController::class, 'destroy'])
    ->name('subscriber.delete')
    ->middleware('feature');
```

---

Database Schema
---------------

[](#database-schema)

```
users
 └─ role_id (foreign key)

roles
 ├─ name
 └─ auto_assign_new_features (boolean)

features
 ├─ slug (e.g., subscriber.create)
 ├─ name
 └─ description

role_has_features (pivot)
 ├─ role_id
 └─ feature_id

```

**Key Design Decisions:**

- One-to-many relationship between Role and User (single role per user)
- Many-to-many relationship between Role and Feature (flexible capability assignment)
- Admin user automatically bypasses all feature checks

---

Authorization Usage
-------------------

[](#authorization-usage)

### Middleware

[](#middleware)

Protect routes with feature-based middleware:

```
Route::post('/subscriber', [SubscriberController::class, 'store'])
    ->name('subscriber.create')
    ->middleware('feature');
```

### Global Enforcement (Optional)

[](#global-enforcement-optional)

You can enforce IAM for all named routes by enabling global enforcement:

```
IAM_ENFORCE_GLOBAL=true

```

When enabled:

- All named routes will be checked using their route name as the feature slug
- Routes with `feature` middleware are respected as-is
- You can opt out per route using `skip-feature`

Example opt-out:

```
Route::get('/health', fn () => 'ok')
    ->middleware('skip-feature');
```

### Gates

[](#gates)

Check permissions programmatically:

```
if (Gate::allows('subscriber.delete')) {
    // Authorized
}

Gate::authorize('subscriber.update');
```

### Blade Directives

[](#blade-directives)

Conditionally render UI elements:

```
@can('subscriber.delete')
    Delete
@endcan

@cannot('subscriber.edit')
    You don't have permission to edit subscribers.
@endcannot
```

### Policy Integration

[](#policy-integration)

Works seamlessly with Laravel Policies:

```
// In SubscriberPolicy
public function delete(User $user, Subscriber $subscriber)
{
    return Gate::allows('subscriber.delete');
}
```

---

Authentication vs Authorization
-------------------------------

[](#authentication-vs-authorization)

Laravel IAM assumes you already authenticate users using Laravel’s auth system (Breeze, Jetstream, Fortify, or custom auth). This package only adds authorization (roles and feature access), and does not implement login, registration, or password management.

---

Testing
-------

[](#testing)

Run the test suite:

```
composer test
```

### Current Test Coverage

[](#current-test-coverage)

The package includes a growing test suite using **Pest**

- ✅ Feature discovery and sync logic
- ✅ Role-feature assignment rules
- ✅ Admin privilege enforcement
- ✅ User authentication flows
- ✅ Gate and policy integration
- ✅ Auto-assignment behavior

### Running Specific Tests

[](#running-specific-tests)

```
# Run feature sync tests
./vendor/bin/pest --filter=FeatureSyncTest

# Run authorization tests
./vendor/bin/pest --filter=AuthorizationTest
```

---

Architecture &amp; Design Patterns
----------------------------------

[](#architecture--design-patterns)

Laravel IAM follows domain-driven design principles and implements several proven patterns:

### Design Patterns

[](#design-patterns)

- **Repository Pattern**: Clean data access layer for models
- **Strategy Pattern**: Multiple authentication providers (local, OAuth)
- **Observer Pattern**: Auto-sync and auto-assignment of features
- **Factory Pattern**: Feature creation from route definitions
- **Policy Pattern**: Integration with Laravel's authorization system

### Domain-Driven Design

[](#domain-driven-design)

- **Bounded Context**: Authorization and authentication as separate concerns
- **Aggregate Root**: Role as the central entity for capability management
- **Value Objects**: Feature keys as immutable identifiers
- **Domain Events**: Feature sync triggers role updates

### Database Design

[](#database-design)

- Normalized schema with proper foreign key constraints
- Pivot table for many-to-many relationships
- Indexed columns for performance (feature keys, role IDs)
- Soft deletes support for audit trails

---

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

[](#configuration)

Publish and customize the configuration file:

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

### Available Options

[](#available-options)

```
return [
    // Database table names
    'tables' => [
        'users' => 'users',
        'roles' => 'roles',
        'features' => 'features',
        'role_has_features' => 'role_has_features',
    ],
];
```

---

Console Commands
----------------

[](#console-commands)

### Core

[](#core)

```
php artisan iam:install
php artisan iam:sync-features
php artisan iam:feature-prune
```

### Roles

[](#roles)

```
php artisan iam:role-create {slug} {name}
php artisan iam:role-assign {user} {role}
php artisan iam:role-feature {role} {features}
php artisan iam:role-list
php artisan iam:role-show {role}
```

### Features

[](#features-1)

```
php artisan iam:feature-create {slug} {name}
php artisan iam:feature-list
```

### Users

[](#users)

```
php artisan iam:user-list
```

---

Philosophy
----------

[](#philosophy)

Laravel IAM follows a **capability-first** model, similar to enterprise IAM systems:

- **AWS IAM**: Actions → Policies → Roles → Users
- **Kubernetes RBAC**: Verbs → Rules → Roles → Subjects
- **OAuth 2.0**: Scopes → Clients → Users

**Core Philosophy:**

```
Capabilities → Roles → Users

```

Instead of asking "What permissions does this user have?", we ask:

> "What features can this user's role access?"

This ensures:

1. **Type Safety**: Features correspond to actual code (routes/controllers)
2. **Maintainability**: Adding a route automatically defines the capability
3. **Consistency**: System capabilities match application capabilities
4. **Auditability**: Clear mapping between code and authorization

---

Roadmap
-------

[](#roadmap)

- Core feature-based authorization
- Automatic feature discovery from routes
- Single-role-per-user model
- Laravel Gate and Blade integration
- Multi-provider authentication support
- Comprehensive test coverage expansion
- API token support (Sanctum integration)
- Service accounts (machine-to-machine auth)
- Policy bridge (Laravel policy generation)
- Audit logs and activity tracking
- Feature grouping and namespaces
- Role inheritance and hierarchies
- Time-based feature access (temporary permissions)

---

Use Cases
---------

[](#use-cases)

### SaaS Applications

[](#saas-applications)

Perfect for multi-tenant SaaS where each customer needs different feature access:

```
// Free tier
$freeRole = Role::create(['name' => 'Free User']);
$freeRole->features()->attach(['post.create', 'post.read']);

// Premium tier
$premiumRole = Role::create(['name' => 'Premium User']);
$premiumRole->features()->attach(['post.create', 'post.read', 'analytics.view', 'export.csv']);
```

### Enterprise Applications

[](#enterprise-applications)

Manage complex organizational hierarchies:

```
// Department-specific capabilities
$hrRole = Role::create(['name' => 'HR Manager']);
$hrRole->features()->attach(['employee.create', 'employee.update', 'payroll.view']);

$financeRole = Role::create(['name' => 'Finance Manager']);
$financeRole->features()->attach(['invoice.create', 'payment.process', 'reports.financial']);
```

### Compliance Systems

[](#compliance-systems)

Track and control access to sensitive operations:

```
// Regulatory compliance
$auditorRole = Role::create(['name' => 'Auditor', 'auto_assign_new_features' => false]);
$auditorRole->features()->attach(['audit.view', 'report.generate']);
// New features require explicit approval for auditors
```

---

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

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

### Development Setup

[](#development-setup)

```
# Clone the repository
git clone https://github.com/euacreations/laravel-iam.git

# Install dependencies
composer install

# Run tests
composer test

# Run static analysis
composer analyse
```

---

License
-------

[](#license)

MIT

---

Credits
-------

[](#credits)

Created by [Eranga Upul Amarakoon](https://github.com/euacreations)

Inspired by enterprise IAM systems and Laravel's elegant authorization system.

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance82

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity49

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

Every ~0 days

Total

4

Last Release

97d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/2ea86b25a0b103d33c68afde82a08edbb358e1bdbd0ac65ee6c24a90ca242d30?d=identicon)[euacreations](/maintainers/euacreations)

---

Top Contributors

[![euacreations](https://avatars.githubusercontent.com/u/25525096?v=4)](https://github.com/euacreations "euacreations (16 commits)")

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/euacreations-laravel-iam/health.svg)

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

###  Alternatives

[fumeapp/modeltyper

Generate TypeScript interfaces from Laravel Models

196277.9k](/packages/fumeapp-modeltyper)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)

PHPackages © 2026

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