定制 apurba-labs/laravel-iam 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

apurba-labs/laravel-iam

Composer 安装命令:

composer require apurba-labs/laravel-iam

包简介

Laravel IAM (Identity & Access Management) package with hierarchical permissions, wildcard support, and SaaS-ready design.

README 文档

README

Latest Version on Packagist Total Downloads License

A powerful, context-aware Identity and Access Management (IAM) system for Laravel. Inspired by AWS IAM, built for modern SaaS architectures.

Quick Example

IAM::can($user, 'inventory.approve', $branchId);
IAM::can($user, 'post.edit')
IAM::usersWithPermission('approval.finance.approve')
IAM::usersWithRole('manager')
IAM::rolesForUser($user)
IAM::permissionsForUser($user)
Example:
IAM::rolesForUser(auth()->user())

Use cases:
profile screens 
admin UI 
audit ordebug
Example:
IAM::permissionsForUser(auth()->user())

Use cases:
effective permission display
debug tools
admin dashboards
policy introspection

Installation

Install the package via composer:

composer require apurba-labs/laravel-iam

Run migrations:

php artisan migrate

Key Features

  • Contextual Scopes: Assign roles to users for specific branches or tenants.
  • Wildcard Logic: Support for resource.*, *.action, and *.* overrides.
  • Action Aliasing: Built-in manage capability (grants all actions for a resource).
  • Developer Friendly: Dynamic Resource & Action registration.
  • Performance First: Built-in caching for permission resolution.

⚖️ Design Philosophy: Contextual Authority

Most RBAC (Role-Based Access Control) packages treat permissions as "Global Flags." In modern SaaS and Enterprise applications, authority is rarely that simple.

Laravel IAM is built on the principle that power is Contextual. A user might be a Manager in the Dhaka Branch but only a Viewer in the Chittagong Branch. Our engine resolves this complexity using a prioritized hierarchy we call the Four Levels of Truth.

🧠 The "Four Levels of Truth"

When you check a permission like invoice.approve, the engine doesn't just look for a string match. It evaluates authority from the broadest scope to the most specific to ensure maximum flexibility and security.

🔑 Permission Hierarchy: "Context-Aware RBAC"

Level Type Example Description
1 Global *.* Full Access: Absolute power across all resources and actions.
2 Resource invoice.* Module Control: Full authority over a specific resource.
3 Action *.approve Action Specialist: Specific action allowed system-wide.
4 Atomic invoice.approve Task Specific: One specific action on one resource.

Performance Note: The engine uses a "Fast-Pass" strategy. If Level 1 or 2 is satisfied, the resolution exits immediately, ensuring that administrative accounts experience zero latency during authorization checks.

🧱 Architectural Design Patterns

Laravel IAM is not just a collection of scripts; it is a structured engine built using industry-standard patterns to ensure scalability and maintainability.

🗄️ Registry Pattern

We use a Registry Pattern for Resource and Action management. This decouples your application's domain logic from the database, allowing you to register permissions dynamically via Service Providers without hitting the database on every boot.

🛡️ Singleton & Manager Pattern

The IAMManager acts as a Singleton within the Laravel Service Container. This ensures a single source of truth for authorization checks during a request lifecycle, enabling efficient memory usage and consistent caching.

🔌 Facade & Proxy Pattern

By providing a Facade, we offer a clean, expressive API (IAM::can()). Internally, this proxies calls to the underlying PermissionResolver, shielding the developer from the complexity of the hierarchical resolution logic.

🔍 Strategy Pattern

The PermissionResolver employs a Strategy Pattern to evaluate permissions. It switches between "Global," "Wildcard," and "Atomic" strategies to find the fastest path to an authorization decision.

🛠 Usage

1. Setup your Model

Implement the Authorizable contract and add the HasRoles trait to your User model. This unlocks the relationship and authority checks.
use ApurbaLabs\IAM\Traits\HasRoles;
use ApurbaLabs\IAM\Contracts\Authorizable;

class User extends Authenticatable implements Authorizable {
    use HasRoles;
}

2. Registering Resources & Actions

Define your application's domain in AppServiceProvider.php. This populates the internal registry used for the "Four Levels of Truth" engine.
Register your modules in `AppServiceProvider.php`:
use ApurbaLabs\IAM\Facades\IAM;

public function boot(): void
{
    IAM::registerResources([
        'expense' => 'Expense Approval',
        'requisition' => 'Requisition',
    ]);

    IAM::registerActions([
        'view',
        'create',
        'approve',
        'reject',
    ]);
}

Default Actions

The IAM system includes a set of built-in default actions.
If you do not explicitly register actions, these defaults will be used automatically.

Default Actions

  • create
  • read
  • update
  • delete
  • list

Workflow Actions

  • publish
  • approve
  • reject
  • refund

Special Actions

  • manage → Grants all actions for a resource
  • * (wildcard) → Full system-level access

Custom Actions

If needed, you can override defaults:

IAM::registerActions([
    'submit',
    'approve',
    'archive',
]);

💡 Tip: Default actions are recommended for most use cases and ensure consistency across modules.

3. Sync Permissions

Run:

php artisan iam:sync-permissions

This will generate permissions like:

  • expense.view
  • expense.approve
  • requisition.create

💡 This approach allows fully dynamic and scalable permission management.

4. Authorization Logic

#### Via Facade
The Facade is the most flexible way to check authority, especially for multi-tenant or scoped applications.
// Global Check (Is this user an Admin anywhere?)
IAM::can($user, 'inventory.view');

// Contextual Check (Is this user a Manager specifically for Branch 101?)
IAM::can($user, 'inventory.approve', 101);
#### Via Middleware

Perfect for protecting API routes. The middleware automatically looks for an X-Scope-ID header to evaluate contextual permissions.
// Single permission check
Route::middleware('iam:inventory.view')->get('/inventory', ...);

// Multiple permissions (OR logic)
Route::middleware('iam:payroll.edit|payroll.manage')->post('/payroll', ...);

5. UI Integration (Blade Magic)

We’ve provided expressive Blade directives to keep your templates clean. No more messy @if blocks.
#### Permission Checks
{{-- Checks if the user can approve in the current branch context --}}
@iam('invoice.approve', 101)
    <button class="btn-success">Approve Invoice</button>
@else
    <span class="text-muted">Read-only Access</span>
@endiam

Role Checks

@{{-- Check for a role in a specific scope --}}
@role('manager', 101)
    <div class="badge">Branch Manager</div>
@endrole

Global UI logic

{{-- If you omit the second argument, the system checks for Global authority (where scope_id is null):}}
@role('admin')
    <nav>System Settings</nav>
@endrole
### 6. Workflow Resolution
Need to find who to notify? Use the resolver to find users with specific authority within a specific scope.
```PHP
// Returns a collection of Users who can approve invoices for Branch 101
$approvers = IAM::usersWithPermission('invoice.approve', 101);

Roadmap

We are committed to making Laravel IAM the standard for contextual authorization. Here is what's coming next:

v0.3.0 - The "Developer Experience" Update

  • Custom Middleware Aliases: Support for @iam:invoice.view,scope_id directly in routes.
  • Policy Integration: Seamless bridge between IAM::can and Laravel's native Gate and Policy system.
  • Audit Logs: A built-in observer to log every permission change for compliance.

v0.4.0 - The "Admin UI" Update

  • Blade Component Library: Pre-built Tailwind components for Role/Permission management.
  • Visual Permission Matrix: A console command to generate a table of who-can-do-what across scopes.

v1.0.0 - Stability & Performance

  • Caching Layer: Redis integration for high-performance permission resolution.
  • API Documentation: Comprehensive documentation site with real-world use cases.
  • Stable Release: Long-term support (LTS) version.
## 🌟 Support the Project

If this package saved you time or simplified your authorization logic:

👉 Give it a **⭐ Star on GitHub**

Your support helps grow the project and bring more advanced features to the community 🚀
---
📄 License
The MIT License (MIT). Please see License File for more information.

apurba-labs/laravel-iam 适用场景与选型建议

apurba-labs/laravel-iam 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 44 次下载、GitHub Stars 达 6, 最近一次更新时间为 2026 年 04 月 02 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「authorization」 「laravel」 「saas」 「permissions」 「rbac」 「access-control」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 apurba-labs/laravel-iam 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 apurba-labs/laravel-iam 我们能提供哪些服务?
定制开发 / 二次开发

基于 apurba-labs/laravel-iam 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 44
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 6
  • 点击次数: 38
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 6
  • Watchers: 0
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-04-02