PHPackages                             litepie/organization - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. litepie/organization

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

litepie/organization
====================

A Laravel package for managing organizational hierarchy with single table structure

v1.0.2(6mo ago)011MITPHPPHP ^8.2CI failing

Since Aug 23Pushed 6mo agoCompare

[ Source](https://github.com/Litepie/Organization)[ Packagist](https://packagist.org/packages/litepie/organization)[ Docs](https://github.com/litepie/organization)[ GitHub Sponsors](https://github.com/litepie)[ RSS](/packages/litepie-organization/feed)WikiDiscussions master Synced 1mo ago

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

Organization Hierarchy Package
==============================

[](#organization-hierarchy-package)

[![Build Status](https://github.com/litepie/organization/actions/workflows/tests.yml/badge.svg)](https://github.com/litepie/organization/actions)[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](LICENSE.md)[![Packagist](https://camo.githubusercontent.com/8c0e380af7820269711ed9580555d4ee60a2008ada16368ef3bb869f3f92a7c9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6c6974657069652f6f7267616e697a6174696f6e2e737667)](https://packagist.org/packages/litepie/organization)[![PHP from Packagist](https://camo.githubusercontent.com/039da440b4624331696d035700d8e590d7eccc5c7e77fcc5f3d83cd6d6170eac/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6c6974657069652f6f7267616e697a6174696f6e)](https://packagist.org/packages/litepie/organization)

[GitHub Repository](https://github.com/litepie/organization)

A Laravel 12 package for managing organizational hierarchy using a single table structure with support for companies, branches, departments, divisions, and sub-divisions. The package includes built-in multi-tenant support for SaaS applications.

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

[](#requirements)

- **PHP 8.2+**
- **Laravel 12.0+**
- MySQL 8.0+ / PostgreSQL 13+ / SQLite 3.35+

Features
--------

[](#features)

- ✅ Laravel 12 compatible with modern PHP features
- 🏢 Single table organization hierarchy
- 🔄 Multiple organization types (company, branch, department, division, sub\_division)
- 👤 Manager assignment with primary and secondary managers
- 👥 User role assignments within organizations
- 🌳 Recursive tree operations with optimized queries
- 🔐 Policy-based authorization with Laravel Gates
- 📡 Event-driven architecture with modern event broadcasting
- 🌐 Comprehensive API and web controllers
- 🏗️ **Multi-tenant support with configurable tenant resolution**
- 🎯 **Enhanced type safety with PHP 8.2+ features**

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

[](#installation)

Install the package via Composer:

```
composer require litepie/organization
```

For multi-tenant applications, also install the Litepie Tenancy package:

```
composer require litepie/tenancy
```

Publish and run the migrations:

```
php artisan vendor:publish --provider="Litepie\Organization\OrganizationServiceProvider" --tag="migrations"
php artisan migrate
```

Publish the configuration file:

```
php artisan vendor:publish --provider="Litepie\Organization\OrganizationServiceProvider" --tag="config"
```

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

[](#configuration)

The configuration file `config/organization.php` allows you to customize:

- Organization types
- Status options
- User model reference
- Route prefixes
- Middleware settings
- **Multi-tenant integration**

### Multi-Tenant Setup

[](#multi-tenant-setup)

This package integrates seamlessly with the [Litepie\\Tenancy](https://github.com/Litepie/Tenancy) package for multi-tenant applications.

1. **Install Litepie Tenancy**:

```
composer require litepie/tenancy
```

2. **Enable tenancy in organization config**:

```
// config/organization.php
'tenancy' => [
    'enabled' => true,
    'tenant_column' => 'tenant_id',
],
```

3. **Configure tenancy package**:

```
php artisan vendor:publish --provider="Litepie\Tenancy\TenancyServiceProvider"
```

4. **Add tenant-aware middleware to routes**:

```
// In your route files
Route::middleware(['tenant.required'])->group(function () {
    Route::apiResource('organizations', OrganizationController::class);
});
```

#### How Multi-Tenancy Works

[](#how-multi-tenancy-works)

When tenancy is enabled:

- Organizations are automatically scoped to the current tenant using the `BelongsToTenant` trait
- All queries are filtered by the current tenant's ID
- New organizations are automatically assigned to the current tenant
- The `tenant_id` column is added to the organizations table

#### Tenant Detection

[](#tenant-detection)

The package uses Litepie\\Tenancy's flexible tenant detection:

```
// Detect by domain
// tenant1.myapp.com -> tenant1

// Detect by header
// X-Tenant-ID: 123

// Detect by authenticated user
// auth()->user()->tenant_id

// Custom detection in your AppServiceProvider
app()->bind(TenantDetectorContract::class, CustomTenantDetector::class);
```

Usage
-----

[](#usage)

### Basic CRUD Operations

[](#basic-crud-operations)

```
use Litepie\Organization\Models\Organization;

// Create a company
$company = Organization::create([
    'type' => 'company',
    'name' => 'Acme Corporation',
    'code' => 'ACME',
    'status' => 'active',
    'created_by' => auth()->id(),
]);

// Create a branch under the company
$branch = Organization::create([
    'parent_id' => $company->id,
    'type' => 'branch',
    'name' => 'New York Branch',
    'code' => 'ACME-NY',
    'status' => 'active',
    'created_by' => auth()->id(),
]);
```

### Multi-Tenant Operations

[](#multi-tenant-operations)

When multi-tenancy is enabled, organizations are automatically scoped to the current tenant:

```
use Litepie\Tenancy\Facades\Tenancy;

// Organizations are automatically filtered by current tenant
$organizations = Organization::all(); // Only current tenant's organizations

// Get current tenant information
$tenant = Tenancy::current();
$tenantId = $tenant?->getTenantId();

// Bypass tenant scoping (admin operations)
$allOrganizations = Organization::withoutTenantScope()->get();

// Manually execute in specific tenant context
$tenant->execute(function () {
    $organizations = Organization::all(); // Scoped to this tenant
});

// Switch tenant context for operations
Tenancy::setTenant($anotherTenant);
$organizations = Organization::all(); // Now scoped to different tenant
```

#### Working with Multiple Tenants

[](#working-with-multiple-tenants)

```
// Get organizations across multiple tenants (admin view)
$crossTenantStats = Organization::withoutTenantScope()
    ->selectRaw('tenant_id, count(*) as total')
    ->groupBy('tenant_id')
    ->get();

// Execute operations for each tenant
foreach (Tenancy::getAllTenants() as $tenant) {
    $tenant->execute(function () use ($tenant) {
        $count = Organization::count();
        echo "Tenant {$tenant->getTenantId()} has {$count} organizations\n";
    });
}
```

### Querying by Type

[](#querying-by-type)

```
// Get all companies
$companies = Organization::ofType('company')->get();

// Get all departments
$departments = Organization::ofType('department')->get();

// Get active organizations
$active = Organization::active()->get();
```

### Working with Hierarchy

[](#working-with-hierarchy)

```
// Get organization tree
$tree = Organization::tree();

// Get children of an organization
$children = $organization->children;

// Get parent organization
$parent = $organization->parent;

// Get all descendants
$descendants = $organization->descendants();

// Get all ancestors
$ancestors = $organization->ancestors();
```

### Manager Assignment

[](#manager-assignment)

```
// Assign primary manager
$organization->update(['manager_id' => $user->id]);

// Assign additional managers with roles
$organization->users()->attach($user->id, ['role' => 'manager']);
$organization->users()->attach($user2->id, ['role' => 'supervisor']);

// Get all managers
$managers = $organization->managers();
```

### User Trait

[](#user-trait)

Add the `HasOrganization` trait to your User model:

```
use Litepie\Organization\Traits\HasOrganization;

class User extends Authenticatable
{
    use HasOrganization;
}
```

Then use it:

```
// Get user's organizations
$organizations = $user->organizations;

// Get user's organizations with specific role
$managedOrganizations = $user->organizationsWithRole('manager');

// Check if user belongs to organization
if ($user->belongsToOrganization($organizationId)) {
    // User belongs to this organization
}
```

API Endpoints
-------------

[](#api-endpoints)

The package provides RESTful API endpoints:

- `GET /api/organizations` - List organizations
- `POST /api/organizations` - Create organization
- `GET /api/organizations/{id}` - Show organization
- `PUT /api/organizations/{id}` - Update organization
- `DELETE /api/organizations/{id}` - Delete organization
- `GET /api/organizations/tree` - Get organization tree
- `POST /api/organizations/{id}/managers` - Assign manager
- `DELETE /api/organizations/{id}/managers/{userId}` - Remove manager

Events
------

[](#events)

The package fires the following events:

- `OrganizationCreated`
- `OrganizationUpdated`
- `OrganizationDeleted`
- `ManagerAssigned`
- `ManagerRemoved`

Testing
-------

[](#testing)

Run the tests:

```
composer test
```

License
-------

[](#license)

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

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance66

Regular maintenance activity

Popularity5

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 83.3% 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 ~59 days

Total

2

Last Release

206d ago

PHP version history (2 changes)v1.0.0PHP ^8.1

v1.0.2PHP ^8.2

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1788735?v=4)[Renfos Technologies](/maintainers/Renfos)[@Renfos](https://github.com/Renfos)

---

Top Contributors

[![georgemjohn](https://avatars.githubusercontent.com/u/7950080?v=4)](https://github.com/georgemjohn "georgemjohn (5 commits)")[![Renfos](https://avatars.githubusercontent.com/u/1788735?v=4)](https://github.com/Renfos "Renfos (1 commits)")

---

Tags

laravelhierarchysaasmulti-tenantcompanybranchorganizationdepartment

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/litepie-organization/health.svg)

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

###  Alternatives

[barryvdh/laravel-ide-helper

Laravel IDE Helper, generates correct PHPDocs for all Facade classes, to improve auto-completion.

14.9k123.0M687](/packages/barryvdh-laravel-ide-helper)[psalm/plugin-laravel

Psalm plugin for Laravel

3274.9M308](/packages/psalm-plugin-laravel)[watson/validating

Eloquent model validating trait.

9723.3M47](/packages/watson-validating)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[hyn/multi-tenant

Run multiple websites using the same laravel installation while keeping tenant specific data separated for fully independant multi-domain setups.

2.6k1.1M9](/packages/hyn-multi-tenant)[aedart/athenaeum

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

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

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