Skip to content

A free open source IT asset/license management system

Added parent company capabilities

snipe91305f1a9dd2
diff --git a/app/Http/Controllers/Api/CompaniesController.php b/app/Http/Controllers/Api/CompaniesController.php
index 484c1bde85..e8e31ee8a8 100644
--- a/app/Http/Controllers/Api/CompaniesController.php
+++ b/app/Http/Controllers/Api/CompaniesController.php
@@ -30,6 +30,7 @@ class CompaniesController extends Controller
$allowed_columns = [
'id',
'name',
+ 'parent_id',
'phone',
'fax',
'email',
@@ -41,6 +42,7 @@ class CompaniesController extends Controller
'accessories_count',
'consumables_count',
'components_count',
+ 'children_count',
'tag_color',
'notes',
];
@@ -48,8 +50,8 @@ class CompaniesController extends Controller
$companies = Company::withCount(['assets as assets_count' => function ($query) {
$query->AssetsForShow();
}])
- ->with('adminuser')
- ->withCount('licenses as licenses_count', 'accessories as accessories_count', 'consumables as consumables_count', 'components as components_count', 'users as users_count');
+ ->with('adminuser', 'parent')
+ ->withCount('licenses as licenses_count', 'accessories as accessories_count', 'consumables as consumables_count', 'components as components_count', 'users as users_count', 'children as children_count');
// This invokes the Searchable model trait scopeTextSearch and will handle input by search or by advanced search filter
if ($request->filled('filter') || $request->filled('search')) {
@@ -72,6 +74,16 @@ class CompaniesController extends Controller
$companies->where('tag_color', '=', $request->input('tag_color'));
}
+ if ($request->filled('parent_id')) {
+ // Allow filtering for top-level companies by passing parent_id=0 or "null".
+ $parentId = $request->input('parent_id');
+ if ($parentId === '0' || strtolower((string) $parentId) === 'null') {
+ $companies->whereNull('parent_id');
+ } else {
+ $companies->where('parent_id', '=', (int) $parentId);
+ }
+ }
+
// Make sure the offset and limit are actually integers and do not exceed system limits
$offset = ($request->input('offset') > $companies->count()) ? $companies->count() : app('api_offset_value');
$limit = app('api_limit_value');
diff --git a/app/Http/Controllers/CompaniesController.php b/app/Http/Controllers/CompaniesController.php
index fa4dd47922..8f98415d49 100644
--- a/app/Http/Controllers/CompaniesController.php
+++ b/app/Http/Controllers/CompaniesController.php
@@ -61,6 +61,7 @@ final class CompaniesController extends Controller
$company = new Company;
$company->name = $request->input('name');
+ $company->parent_id = $request->input('parent_id') ?: null;
$company->phone = $request->input('phone');
$company->fax = $request->input('fax');
$company->email = $request->input('email');
@@ -108,6 +109,7 @@ final class CompaniesController extends Controller
$this->authorize('update', $company);
$company->name = $request->input('name');
+ $company->parent_id = $request->input('parent_id') ?: null;
$company->phone = $request->input('phone');
$company->fax = $request->input('fax');
$company->email = $request->input('email');
diff --git a/app/Http/Transformers/CompaniesTransformer.php b/app/Http/Transformers/CompaniesTransformer.php
index af60ceab49..964b6b02e7 100644
--- a/app/Http/Transformers/CompaniesTransformer.php
+++ b/app/Http/Transformers/CompaniesTransformer.php
@@ -31,6 +31,11 @@ class CompaniesTransformer
'email' => ($company->email != '') ? e($company->email) : null,
'image' => ($company->image) ? Storage::disk('public')->url('companies/'.e($company->image)) : null,
'qr_code_url' => route('qr_code/common', ['object_type' => 'companies', 'id' => $company->id]),
+ 'parent' => ($company->parent) ? [
+ 'id' => (int) $company->parent->id,
+ 'name' => e($company->parent->name),
+ ] : null,
+ 'children_count' => (int) ($company->children_count ?? $company->children()->count()),
'assets_count' => (int) $company->assets_count,
'licenses_count' => (int) $company->licenses_count,
'accessories_count' => (int) $company->accessories_count,
diff --git a/app/Models/Company.php b/app/Models/Company.php
index fe8500943d..abb9321c86 100644
--- a/app/Models/Company.php
+++ b/app/Models/Company.php
@@ -39,6 +39,11 @@ final class Company extends SnipeModel
'fax' => 'min:7|max:35|nullable',
'phone' => 'min:7|max:35|nullable',
'email' => 'email|max:150|nullable',
+ 'parent_id' => 'nullable|integer|exists:companies,id|one_level_deep:companies,id',
+ ];
+
+ protected $casts = [
+ 'parent_id' => 'integer',
];
protected $presenter = CompanyPresenter::class;
@@ -88,6 +93,7 @@ final class Company extends SnipeModel
*/
protected $fillable = [
'name',
+ 'parent_id',
'phone',
'fax',
'email',
@@ -101,6 +107,11 @@ final class Company extends SnipeModel
* We deliberately bypass the Eloquent companies() relationship here because
* loading that relationship triggers CompanyableScope on the Company model,
* which calls this method again — infinite recursion.
+ *
+ * If a user is a member of a parent company, they implicitly have access to
+ * all of that company's children too. We expand the direct pivot set by
+ * pulling in children of any directly-assigned company. The one-level-deep
+ * constraint enforced by validation means a single child lookup is sufficient.
*/
private static function getCurrentUserCompanyIds(): array
{
@@ -108,10 +119,21 @@ final class Company extends SnipeModel
return [];
}
- return DB::table('company_user')
+ $directIds = DB::table('company_user')
->where('user_id', auth()->id())
->pluck('company_id')
->toArray();
+
+ if (empty($directIds)) {
+ return [];
+ }
+
+ $childIds = DB::table('companies')
+ ->whereIn('parent_id', $directIds)
+ ->pluck('id')
+ ->toArray();
+
+ return array_values(array_unique(array_merge($directIds, $childIds)));
}
public static function isFullMultipleCompanySupportEnabled()
@@ -312,7 +334,8 @@ final class Company extends SnipeModel
&& (($this->components_count ?? $this->components()->count()) === 0)
&& (($this->consumables_count ?? $this->consumables()->count()) === 0)
&& (($this->accessories_count ?? $this->accessories()->count()) === 0)
- && (($this->users_count ?? $this->users()->count()) === 0);
+ && (($this->users_count ?? $this->users()->count()) === 0)
+ && (($this->children_count ?? $this->children()->count()) === 0);
}
/**
@@ -332,6 +355,23 @@ final class Company extends SnipeModel
return $this->belongsToMany(User::class, 'company_user');
}
+ /**
+ * Parent company (one level only — children cannot themselves have children).
+ */
+ public function parent()
+ {
+ return $this->belongsTo(self::class, 'parent_id');
+ }
+
+ /**
+ * Child companies. The one-level-deep validator on parent_id guarantees
+ * children of a child cannot be created, so this is the full descendant set.
+ */
+ public function children()
+ {
+ return $this->hasMany(self::class, 'parent_id');
+ }
+
public function assets()
{
return $this->hasMany(Asset::class, 'company_id');
diff --git a/app/Models/User.php b/app/Models/User.php
index 3f3f357fe2..e73ca7cad1 100644
--- a/app/Models/User.php
+++ b/app/Models/User.php
@@ -649,17 +649,34 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo
return (bool) Setting::getSettings()->null_company_is_floater;
}
- return $userCompanyIds->contains($companyId);
+ if ($userCompanyIds->contains($companyId)) {
+ return true;
+ }
+
+ // Membership in a parent company implies access to its children — accept
+ // an item from a child company when the user belongs to its parent.
+ return DB::table('companies')
+ ->where('id', $companyId)
+ ->whereIn('parent_id', $userCompanyIds)
+ ->exists();
}
/**
- * Returns all companies this user belongs to — union of the primary company_id
- * column and the many-to-many pivot — as a deduplicated Collection.
+ * Returns all companies this user has access to — the pivot memberships plus
+ * any child companies of those memberships (one-level-deep hierarchy).
* Used to scope FMCS dropdowns to companies the user is allowed to work with.
*/
public function allCompanies(): Collection
{
- return $this->companies->unique('id')->values();
+ $direct = $this->companies->unique('id');
+
+ if ($direct->isEmpty()) {
+ return $direct->values();
+ }
+
+ $children = Company::whereIn('parent_id', $direct->pluck('id'))->get();
+
+ return $direct->concat($children)->unique('id')->values();
}
/**
diff --git a/app/Providers/ValidationServiceProvider.php b/app/Providers/ValidationServiceProvider.php
index 91772cbd95..6228b9e937 100644
--- a/app/Providers/ValidationServiceProvider.php
+++ b/app/Providers/ValidationServiceProvider.php
@@ -181,6 +181,57 @@ class ValidationServiceProvider extends ServiceProvider
return true;
});
+ // Enforce a one-level-deep self-referential hierarchy.
+ //
+ // Used on parent_id columns where we explicitly do NOT want grandparents:
+ // a row may be a top-level (parent_id null) or a child of a top-level,
+ // but a child cannot itself become a parent, and a row that already has
+ // children cannot be assigned a parent.
+ //
+ // Example usage on Company (parent_id self-references the same table):
+ // 'parent_id' => 'one_level_deep:companies,id'
+ //
+ // Fails when:
+ // - the chosen parent is the row itself (self-parent)
+ // - the chosen parent itself has a parent (would create depth > 1)
+ // - the row being saved already has children (would create depth > 1)
+ Validator::extend('one_level_deep', function ($attribute, $value, $parameters, $validator) {
+ if (is_null($value) || $value === '') {
+ return true;
+ }
+
+ if (count($parameters) < 2) {
+ throw new \Exception('Required validator parameters: <table>,<primary key>');
+ }
+
+ $table = $parameters[0];
+ $pk = $parameters[1];
+
+ $data = $validator->getData();
+ $modelId = $data[$pk] ?? null;
+
+ // Self-parent is never allowed.
+ if ($modelId && (int) $modelId === (int) $value) {
+ return false;
+ }
+
+ // The chosen parent must itself be a top-level (parent_id IS NULL).
+ $chosenParentParentId = DB::table($table)->where($pk, $value)->value('parent_id');
+ if (! is_null($chosenParentParentId)) {
+ return false;
+ }
+
+ // If this row already has children, it cannot be moved under another parent.
+ if ($modelId) {
+ $hasChildren = DB::table($table)->where('parent_id', $modelId)->exists();
+ if ($hasChildren) {
+ return false;
+ }
+ }
+
+ return true;
+ });
+
// Yo dawg. I heard you like validators.
// This validates the custom validator regex in custom fields.
// We're just checking that the regex won't throw an exception, not
diff --git a/database/factories/CompanyFactory.php b/database/factories/CompanyFactory.php
index e9f2cb0669..a6d97c9db7 100644
--- a/database/factories/CompanyFactory.php
+++ b/database/factories/CompanyFactory.php
@@ -28,4 +28,9 @@ class CompanyFactory extends Factory
'tag_color' => $this->faker->hexColor(),
];
}
+
+ public function childOf(Company $parent): static
+ {
+ return $this->state(['parent_id' => $parent->id]);
+ }
}
diff --git a/database/migrations/2026_06_22_000001_add_parent_id_to_companies_table.php b/database/migrations/2026_06_22_000001_add_parent_id_to_companies_table.php
new file mode 100644
index 0000000000..4e47dd6864
--- /dev/null
+++ b/database/migrations/2026_06_22_000001_add_parent_id_to_companies_table.php
@@ -0,0 +1,23 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration
+{
+ public function up(): void
+ {
+ Schema::table('companies', function (Blueprint $table) {
+ $table->unsignedBigInteger('parent_id')->nullable()->after('name')->index();
+ });
+ }
+
+ public function down(): void
+ {
+ Schema::table('companies', function (Blueprint $table) {
+ $table->dropIndex(['parent_id']);
+ $table->dropColumn('parent_id');
+ });
+ }
+};
diff --git a/resources/lang/en-US/admin/companies/table.php b/resources/lang/en-US/admin/companies/table.php
index 425ff0ee20..50bab54c02 100644
--- a/resources/lang/en-US/admin/companies/table.php
+++ b/resources/lang/en-US/admin/companies/table.php
@@ -9,4 +9,6 @@ return [
'update' => 'Update Company',
'name' => 'Company Name',
'id' => 'ID',
+ 'parent' => 'Parent Company',
+ 'parent_help' => 'Optional. If set, this company is a child of the selected parent. Users assigned to the parent automatically have access to this company. Only one level of nesting is allowed.',
];
diff --git a/resources/lang/en-US/validation.php b/resources/lang/en-US/validation.php
index 7ae4cb26d3..3ce37a8de5 100644
--- a/resources/lang/en-US/validation.php
+++ b/resources/lang/en-US/validation.php
@@ -160,6 +160,7 @@ return [
'two_column_unique_undeleted' => 'The :attribute must be unique across :table1 and :table2. ',
'unique_undeleted' => 'The :attribute must be unique.',
'non_circular' => 'The :attribute must not create a circular reference.',
+ 'one_level_deep' => 'The :attribute must be a top-level item, and this item must not already have children. Only one level of nesting is allowed.',
'not_array' => ':attribute cannot be an array.',
'disallow_same_pwd_as_user_fields' => 'Password cannot be the same as the username.',
'letters' => 'Password must contain at least one letter.',
diff --git a/resources/views/companies/edit.blade.php b/resources/views/companies/edit.blade.php
index 1382b22921..15c3ed90d9 100644
--- a/resources/views/companies/edit.blade.php
+++ b/resources/views/companies/edit.blade.php
@@ -25,6 +25,11 @@
name="name"
/>
+ @include('partials.forms.edit.company-select', [
+ 'translated_name' => trans('admin/companies/table.parent'),
+ 'fieldname' => 'parent_id',
+ ])
+
<x-form.row
:label="trans('admin/suppliers/table.phone')"
:$item
diff --git a/tests/Feature/Companies/Api/CompanyHierarchyTest.php b/tests/Feature/Companies/Api/CompanyHierarchyTest.php
new file mode 100644
index 0000000000..aa8f828d51
--- /dev/null
+++ b/tests/Feature/Companies/Api/CompanyHierarchyTest.php
@@ -0,0 +1,263 @@
+<?php
+
+namespace Tests\Feature\Companies\Api;
+
+use App\Models\Asset;
+use App\Models\Company;
+use App\Models\User;
+use Tests\TestCase;
+
+class CompanyHierarchyTest extends TestCase
+{
+ public function test_can_create_company_with_parent_id()
+ {
+ $parent = Company::factory()->create();
+
+ $this->actingAsForApi(User::factory()->createCompanies()->create())
+ ->postJson(route('api.companies.store'), [
+ 'name' => 'Subsidiary',
+ 'parent_id' => $parent->id,
+ ])
+ ->assertStatus(200)
+ ->assertStatusMessageIs('success');
+
+ $this->assertDatabaseHas('companies', [
+ 'name' => 'Subsidiary',
+ 'parent_id' => $parent->id,
+ ]);
+ }
+
+ public function test_can_update_company_to_set_parent_id()
+ {
+ $parent = Company::factory()->create();
+ $orphan = Company::factory()->create();
+
+ $this->actingAsForApi(User::factory()->editCompanies()->create())
+ ->patchJson(route('api.companies.update', ['company' => $orphan->id]), [
+ 'name' => $orphan->name,
+ 'parent_id' => $parent->id,
+ ])
+ ->assertStatus(200)
+ ->assertStatusMessageIs('success');
+
+ $this->assertEquals($parent->id, $orphan->fresh()->parent_id);
+ }
+
+ public function test_company_cannot_be_its_own_parent()
+ {
+ $company = Company::factory()->create();
+
+ $this->actingAsForApi(User::factory()->editCompanies()->create())
+ ->patchJson(route('api.companies.update', ['company' => $company->id]), [
+ 'name' => $company->name,
+ 'parent_id' => $company->id,
+ ])
+ ->assertStatus(200)
+ ->assertStatusMessageIs('error')
+ ->assertJsonStructure(['messages' => ['parent_id']]);
+
+ $this->assertNull($company->fresh()->parent_id);
+ }
+
+ public function test_cannot_create_grandchild_company()
+ {
+ // Grandparent → Parent already exists; trying to make Child the parent of New should fail.
+ $grandparent = Company::factory()->create();
+ $parent = Company::factory()->childOf($grandparent)->create();
+
+ $this->actingAsForApi(User::factory()->createCompanies()->create())
+ ->postJson(route('api.companies.store'), [
+ 'name' => 'GreatGrandchild',
+ 'parent_id' => $parent->id,
+ ])
+ ->assertStatus(200)
+ ->assertStatusMessageIs('error')
+ ->assertJsonStructure(['messages' => ['parent_id']]);
+
+ $this->assertDatabaseMissing('companies', ['name' => 'GreatGrandchild']);
+ }
+
+ public function test_cannot_assign_parent_to_company_that_has_children()
+ {
+ $grandparentCandidate = Company::factory()->create();
+ $parent = Company::factory()->create();
+ Company::factory()->childOf($parent)->create();
+
+ $this->actingAsForApi(User::factory()->editCompanies()->create())
+ ->patchJson(route('api.companies.update', ['company' => $parent->id]), [
+ 'name' => $parent->name,
+ 'parent_id' => $grandparentCandidate->id,
+ ])
+ ->assertStatus(200)
+ ->assertStatusMessageIs('error')
+ ->assertJsonStructure(['messages' => ['parent_id']]);
+
+ $this->assertNull($parent->fresh()->parent_id);
+ }
+
+ public function test_can_clear_parent_id_by_passing_null()
+ {
+ $parent = Company::factory()->create();
+ $child = Company::factory()->childOf($parent)->create();
+
+ $this->actingAsForApi(User::factory()->editCompanies()->create())
+ ->patchJson(route('api.companies.update', ['company' => $child->id]), [
+ 'name' => $child->name,
+ 'parent_id' => null,
+ ])
+ ->assertStatus(200)
+ ->assertStatusMessageIs('success');
+
+ $this->assertNull($child->fresh()->parent_id);
+ }
+
+ public function test_parent_id_must_reference_existing_company()
+ {
+ $this->actingAsForApi(User::factory()->createCompanies()->create())
+ ->postJson(route('api.companies.store'), [
+ 'name' => 'Orphaned',
+ 'parent_id' => 999999,
+ ])
+ ->assertStatus(200)
+ ->assertStatusMessageIs('error')
+ ->assertJsonStructure(['messages' => ['parent_id']]);
+ }
+
+ public function test_cannot_delete_company_that_has_children()
+ {
+ $parent = Company::factory()->create();
+ Company::factory()->childOf($parent)->create();
+
+ $this->actingAsForApi(User::factory()->deleteCompanies()->create())
+ ->deleteJson(route('api.companies.destroy', $parent))
+ ->assertStatusMessageIs('error');
+
+ $this->assertDatabaseHas('companies', ['id' => $parent->id, 'deleted_at' => null]);
+ }
+
+ public function test_index_exposes_parent_and_children_count()
+ {
+ $parent = Company::factory()->create();
+ Company::factory()->count(2)->childOf($parent)->create();
+
+ $response = $this->actingAsForApi(User::factory()->superuser()->create())
+ ->getJson(route('api.companies.index', ['search' => $parent->name]))
+ ->assertOk()
+ ->json();
+
+ $parentRow = collect($response['rows'])->firstWhere('id', $parent->id);
+
+ $this->assertNotNull($parentRow);
+ $this->assertNull($parentRow['parent']);
+ $this->assertEquals(2, $parentRow['children_count']);
+ }
+
+ public function test_show_exposes_parent_block_for_child_company()
+ {
+ $parent = Company::factory()->create();
+ $child = Company::factory()->childOf($parent)->create();
+
+ $response = $this->actingAsForApi(User::factory()->superuser()->create())
+ ->getJson(route('api.companies.show', $child))
+ ->assertOk()
+ ->json();
+
+ $this->assertEquals($parent->id, $response['parent']['id']);
+ $this->assertEquals($parent->name, $response['parent']['name']);
+ }
+
+ public function test_user_in_parent_company_has_fmcs_access_to_child_company_assets()
+ {
+ $this->settings->enableMultipleFullCompanySupport();
+
+ $parent = Company::factory()->create();
+ $child = Company::factory()->childOf($parent)->create();
+
+ // Asset belongs to the child company.
+ $assetInChild = Asset::factory()->create(['company_id' => $child->id]);
+
+ // User is a member of the parent only.
+ $userInParent = $parent->users()->save(User::factory()->viewAssets()->create());
+
+ $response = $this->actingAsForApi($userInParent)
+ ->getJson(route('api.assets.index'))
+ ->assertOk()
+ ->json();
+
+ $foundIds = collect($response['rows'])->pluck('id')->all();
+
+ $this->assertContains($assetInChild->id, $foundIds, 'User in parent should see child-company assets');
+ }
+
+ public function test_user_in_child_company_does_not_see_parent_company_assets()
+ {
+ $this->settings->enableMultipleFullCompanySupport();
+
+ $parent = Company::factory()->create();
+ $child = Company::factory()->childOf($parent)->create();
+
+ $assetInParent = Asset::factory()->create(['company_id' => $parent->id]);
+
+ $userInChild = $child->users()->save(User::factory()->viewAssets()->create());
+
+ $response = $this->actingAsForApi($userInChild)
+ ->getJson(route('api.assets.index'))
+ ->assertOk()
+ ->json();
+
+ $foundIds = collect($response['rows'])->pluck('id')->all();
+
+ $this->assertNotContains($assetInParent->id, $foundIds, 'User in child should not see parent-company assets');
+ }
+
+ public function test_user_in_parent_can_filter_companies_selectlist_and_see_children()
+ {
+ $this->settings->enableMultipleFullCompanySupport();
+
+ $parent = Company::factory()->create();
+ $child = Company::factory()->childOf($parent)->create();
+ $unrelated = Company::factory()->create();
+
+ // view.selectlists is gated on having create/update on at least one resource.
+ $userInParent = $parent->users()->save(User::factory()->createAssets()->create());
+
+ $response = $this->actingAsForApi($userInParent)
+ ->getJson(route('api.companies.selectlist'))
+ ->assertOk()
+ ->json();
+
+ $ids = collect($response['results'])->pluck('id')->all();
+
+ $this->assertContains($parent->id, $ids);
+ $this->assertContains($child->id, $ids);
+ $this->assertNotContains($unrelated->id, $ids);
+ }
+
+ public function test_fmcs_floater_mode_still_works_with_hierarchy()
+ {
+ // Floater mode: items with NULL company_id are visible to everyone.
+ // A user in a parent company should still see floater items in addition
+ // to their parent's items AND their child-company items.
+ $this->settings->enableFloaterMode();
+
+ $parent = Company::factory()->create();
+ $child = Company::factory()->childOf($parent)->create();
+
+ $assetInParent = Asset::factory()->create(['company_id' => $parent->id]);
+ $assetInChild = Asset::factory()->create(['company_id' => $child->id]);
+ $floaterAsset = Asset::factory()->create(['company_id' => null]);
+
+ $userInParent = $parent->users()->save(User::factory()->viewAssets()->create());
+
+ $response = $this->actingAsForApi($userInParent)
+ ->getJson(route('api.assets.index'))
+ ->assertOk()
+ ->json();
+
+ $foundIds = collect($response['rows'])->pluck('id')->all();
+
+ $this->assertContains($assetInParent->id, $foundIds, 'Parent asset should be visible');
+ $this->assertContains($assetInChild->id, $foundIds, 'Child asset should be visible via hierarchy');
+ $this->assertContains($floaterAsset->id, $foundIds, 'Floater asset should be visible via null_company_is_floater');
+ }
+}