{"id":20300955,"url":"https://github.com/rinvex/laravel-categories","last_synced_at":"2025-05-16T01:05:25.339Z","repository":{"id":33097729,"uuid":"87599972","full_name":"rinvex/laravel-categories","owner":"rinvex","description":"Rinvex Categorizable is a polymorphic Laravel package, for category management. You can categorize any eloquent model with ease, and utilize the power of Nested Sets, and the awesomeness of Sluggable, and Translatable models out of the box.","archived":false,"fork":false,"pushed_at":"2023-07-03T13:29:53.000Z","size":354,"stargazers_count":467,"open_issues_count":2,"forks_count":69,"subscribers_count":14,"default_branch":"master","last_synced_at":"2025-04-27T11:46:02.407Z","etag":null,"topics":["categories","classification","laravel","php","taxonomy"],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rinvex.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2017-04-08T01:47:00.000Z","updated_at":"2025-03-11T13:41:07.000Z","dependencies_parsed_at":"2023-10-03T04:32:38.511Z","dependency_job_id":null,"html_url":"https://github.com/rinvex/laravel-categories","commit_stats":null,"previous_names":[],"tags_count":40,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rinvex%2Flaravel-categories","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rinvex%2Flaravel-categories/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rinvex%2Flaravel-categories/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rinvex%2Flaravel-categories/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rinvex","download_url":"https://codeload.github.com/rinvex/laravel-categories/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254448579,"owners_count":22072764,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["categories","classification","laravel","php","taxonomy"],"created_at":"2024-11-14T16:22:40.963Z","updated_at":"2025-05-16T01:05:23.987Z","avatar_url":"https://github.com/rinvex.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Rinvex Categories\n\n**Rinvex Categories** is a polymorphic Laravel package, for category management. You can categorize any eloquent model with ease, and utilize the power of **[Nested Sets](https://github.com/lazychaser/laravel-nestedset)**, and the awesomeness of **[Sluggable](https://github.com/spatie/laravel-sluggable)**, and **[Translatable](https://github.com/spatie/laravel-translatable)** models out of the box.\n\n[![Packagist](https://img.shields.io/packagist/v/rinvex/laravel-categories.svg?label=Packagist\u0026style=flat-square)](https://packagist.org/packages/rinvex/laravel-categories)\n[![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/rinvex/laravel-categories.svg?label=Scrutinizer\u0026style=flat-square)](https://scrutinizer-ci.com/g/rinvex/laravel-categories/)\n[![Travis](https://img.shields.io/travis/rinvex/laravel-categories.svg?label=TravisCI\u0026style=flat-square)](https://travis-ci.org/rinvex/laravel-categories)\n[![StyleCI](https://styleci.io/repos/87599972/shield)](https://styleci.io/repos/87599972)\n[![License](https://img.shields.io/packagist/l/rinvex/laravel-categories.svg?label=License\u0026style=flat-square)](https://github.com/rinvex/laravel-categories/blob/develop/LICENSE)\n\n\n## Installation\n\n1. Install the package via composer:\n    ```shell\n    composer require rinvex/laravel-categories\n    ```\n\n2. Publish resources (migrations and config files):\n    ```shell\n    php artisan rinvex:publish:categories\n    ```\n\n3. Execute migrations via the following command:\n    ```shell\n    php artisan rinvex:migrate:categories\n    ```\n\n4. Done!\n\n\n## Usage\n\nTo add categories support to your eloquent models simply use `\\Rinvex\\Categories\\Traits\\Categorizable` trait.\n\n### Manage your categories\n\nYour categories are just normal [eloquent](https://laravel.com/docs/master/eloquent) models, so you can deal with it like so. Nothing special here!\n\n\u003e **Notes:** since **Rinvex Categories** extends and utilizes other awesome packages, checkout the following documentations for further details:\n\u003e - Powerful Nested Sets using [`kalnoy/nestedset`](https://github.com/lazychaser/laravel-nestedset)\n\u003e - Automatic Slugging using [`spatie/laravel-sluggable`](https://github.com/spatie/laravel-sluggable)\n\u003e - Translatable out of the box using [`spatie/laravel-translatable`](https://github.com/spatie/laravel-translatable)\n\n### Manage your categorizable model\n\nThe API is intutive and very straightforward, so let's give it a quick look:\n\n```php\n// Get all categories\n$allCategories = app('rinvex.categories.category')-\u003eall();\n\n// Get instance of your model\n$post = new \\App\\Models\\Post::find(123);\n\n// Get attached categories collection\n$post-\u003ecategories;\n\n// Get attached categories query builder\n$post-\u003ecategories();\n```\n\nYou can attach categories in various ways:\n\n```php\n// Single category id\n$post-\u003eattachCategories(1);\n\n// Multiple category IDs array\n$post-\u003eattachCategories([1, 2, 5]);\n\n// Multiple category IDs collection\n$post-\u003eattachCategories(collect([1, 2, 5]));\n\n// Single category model instance\n$categoryInstance = app('rinvex.categories.category')-\u003efirst();\n$post-\u003eattachCategories($categoryInstance);\n\n// Single category slug\n$post-\u003eattachCategories('test-category');\n\n// Multiple category slugs array\n$post-\u003eattachCategories(['first-category', 'second-category']);\n\n// Multiple category slugs collection\n$post-\u003eattachCategories(collect(['first-category', 'second-category']));\n\n// Multiple category model instances\n$categoryInstances = app('rinvex.categories.category')-\u003ewhereIn('id', [1, 2, 5])-\u003eget();\n$post-\u003eattachCategories($categoryInstances);\n```\n\n\u003e **Notes:** \n\u003e - The `attachCategories()` method attach the given categories to the model without touching the currently attached categories, while there's the `syncCategories()` method that can detach any records that's not in the given items, this method takes a second optional boolean parameter that's set detaching flag to `true` or `false`.\n\u003e - To detach model categories you can use the `detachCategories()` method, which uses **exactly** the same signature as the `attachCategories()` method, with additional feature of detaching all currently attached categories by passing null or nothing to that method as follows: `$post-\u003edetachCategories();`.\n\nAnd as you may have expected, you can check if categories attached:\n\n```php\n// Single category id\n$post-\u003ehasAnyCategories(1);\n\n// Multiple category IDs array\n$post-\u003ehasAnyCategories([1, 2, 5]);\n\n// Multiple category IDs collection\n$post-\u003ehasAnyCategories(collect([1, 2, 5]));\n\n// Single category model instance\n$categoryInstance = app('rinvex.categories.category')-\u003efirst();\n$post-\u003ehasAnyCategories($categoryInstance);\n\n// Single category slug\n$post-\u003ehasAnyCategories('test-category');\n\n// Multiple category slugs array\n$post-\u003ehasAnyCategories(['first-category', 'second-category']);\n\n// Multiple category slugs collection\n$post-\u003ehasAnyCategories(collect(['first-category', 'second-category']));\n\n// Multiple category model instances\n$categoryInstances = app('rinvex.categories.category')-\u003ewhereIn('id', [1, 2, 5])-\u003eget();\n$post-\u003ehasAnyCategories($categoryInstances);\n```\n\n\u003e **Notes:** \n\u003e - The `hasAnyCategories()` method check if **ANY** of the given categories are attached to the model. It returns boolean `true` or `false` as a result.\n\u003e - Similarly the `hasAllCategories()` method uses **exactly** the same signature as the `hasAnyCategories()` method, but it behaves differently and performs a strict comparison to check if **ALL** of the given categories are attached.\n\n### Advanced usage\n\n#### Generate category slugs\n\n**Rinvex Categories** auto generates slugs and auto detect and insert default translation for you if not provided, but you still can pass it explicitly through normal eloquent `create` method, as follows:\n\n```php\napp('rinvex.categories.category')-\u003ecreate(['name' =\u003e ['en' =\u003e 'My New Category'], 'slug' =\u003e 'custom-category-slug']);\n```\n\n\u003e **Note:** Check **[Sluggable](https://github.com/spatie/laravel-sluggable)** package for further details.\n\n#### Smart parameter detection\n\n**Rinvex Categories** methods that accept list of categories are smart enough to handle almost all kinds of inputs as you've seen in the above examples. It will check input type and behave accordingly. \n\n#### Retrieve all models attached to the category\n\nYou may encounter a situation where you need to get all models attached to certain category, you do so with ease as follows:\n\n```php\n$category = app('rinvex.categories.category')-\u003efind(1);\n$category-\u003eentries(\\App\\Models\\Post::class)-\u003eget();\n```\n\n#### Query scopes\n\nYes, **Rinvex Categories** shipped with few awesome query scopes for your convenience, usage example:\n\n```php\n// Single category id\n$post-\u003ewithAnyCategories(1)-\u003eget();\n\n// Multiple category IDs array\n$post-\u003ewithAnyCategories([1, 2, 5])-\u003eget();\n\n// Multiple category IDs collection\n$post-\u003ewithAnyCategories(collect([1, 2, 5]))-\u003eget();\n\n// Single category model instance\n$categoryInstance = app('rinvex.categories.category')-\u003efirst();\n$post-\u003ewithAnyCategories($categoryInstance)-\u003eget();\n\n// Single category slug\n$post-\u003ewithAnyCategories('test-category')-\u003eget();\n\n// Multiple category slugs array\n$post-\u003ewithAnyCategories(['first-category', 'second-category'])-\u003eget();\n\n// Multiple category slugs collection\n$post-\u003ewithAnyCategories(collect(['first-category', 'second-category']))-\u003eget();\n\n// Multiple category model instances\n$categoryInstances = app('rinvex.categories.category')-\u003ewhereIn('id', [1, 2, 5])-\u003eget();\n$post-\u003ewithAnyCategories($categoryInstances)-\u003eget();\n```\n\n\u003e **Notes:**\n\u003e - The `withAnyCategories()` scope finds posts with **ANY** attached categories of the given. It returns normally a query builder, so you can chain it or call `get()` method for example to execute and get results.\n\u003e - Similarly there's few other scopes like `withAllCategories()` that finds posts with **ALL** attached categories of the given, `withoutCategories()` which finds posts without **ANY** attached categories of the given, and lastly `withoutAnyCategories()` which find posts without **ANY** attached categories at all. All scopes are created equal, with same signature, and returns query builder.\n\n#### Category translations\n\nManage category translations with ease as follows:\n\n```php\n$category = app('rinvex.categories.category')-\u003efind(1);\n\n// Update title translations\n$category-\u003esetTranslation('name', 'en', 'New English Category Title')-\u003esave();\n\n// Alternatively you can use default eloquent update\n$category-\u003eupdate([\n    'name' =\u003e [\n        'en' =\u003e 'New Category',\n        'ar' =\u003e 'تصنيف جديد',\n    ],\n]);\n\n// Get single category translation\n$category-\u003egetTranslation('name', 'en');\n\n// Get all category translations\n$category-\u003egetTranslations('name');\n\n// Get category title in default locale\n$category-\u003ename;\n```\n\n\u003e **Note:** Check **[Translatable](https://github.com/spatie/laravel-translatable)** package for further details.\n\n___\n\n## Manage your nodes/nestedsets\n\n- [Inserting Categories](#inserting-categories)\n    - [Creating categories](#creating-categories)\n    - [Making a root from existing category](#making-a-root-from-existing-category)\n    - [Appending and prepending to the specified parent](#appending-and-prepending-to-the-specified-parent)\n    - [Inserting before or after specified category](#inserting-before-or-after-specified-category)\n    - [Building a tree from array](#building-a-tree-from-array)\n    - [Rebuilding a tree from array](#rebuilding-a-tree-from-array)\n- [Retrieving categories](#retrieving-categories)\n    - [Ancestors](#ancestors)\n    - [Descendants](#descendants)\n    - [Siblings](#siblings)\n    - [Getting related models from other table](#getting-related-models-from-other-table)\n    - [Including category depth](#including-category-depth)\n    - [Default order](#default-order)\n        - [Shifting a category](#shifting-a-category)\n    - [Constraints](#constraints)\n    - [Building a tree](#building-a-tree)\n        - [Building flat tree](#building-flat-tree)\n        - [Getting a subtree](#getting-a-subtree)\n- [Deleting categories](#deleting-categories)\n- [Helper methods](#helper-methods)\n- [Checking consistency](#checking-consistency)\n    - [Fixing tree](#fixing-tree)\n\n### Inserting categories\n\nMoving and inserting categories includes several database queries, so **transaction is automatically started**\nwhen category is saved. It is safe to use global transaction if you work with several models.\n\nAnother important note is that **structural manipulations are deferred** until you hit `save` on model\n(some methods implicitly call `save` and return boolean result of the operation).\n\nIf model is successfully saved it doesn't mean that category was moved. If your application\ndepends on whether the category has actually changed its position, use `hasMoved` method:\n\n```php\nif ($category-\u003esave()) {\n    $moved = $category-\u003ehasMoved();\n}\n```\n\n#### Creating categories\n\nWhen you simply create a category, it will be appended to the end of the tree:\n\n```php\napp('rinvex.categories.category')-\u003ecreate($attributes); // Saved as root\n\n$category = app('rinvex.categories.category')-\u003efill($attributes);\n$category-\u003esave(); // Saved as root\n```\n\nIn this case the category is considered a _root_ which means that it doesn't have a parent.\n\n#### Making a root from existing category\n\nThe category will be appended to the end of the tree:\n\n```php\n// #1 Implicit save\n$category-\u003esaveAsRoot();\n\n// #2 Explicit save\n$category-\u003emakeRoot()-\u003esave();\n```\n\n#### Appending and prepending to the specified parent\n\nIf you want to make category a child of other category, you can make it last or first child.\nSuppose that `$parent` is some existing category, there are few ways to append a category:\n\n```php\n// #1 Using deferred insert\n$category-\u003eappendToNode($parent)-\u003esave();\n\n// #2 Using parent category\n$parent-\u003eappendNode($category);\n\n// #3 Using parent's children relationship\n$parent-\u003echildren()-\u003ecreate($attributes);\n\n// #5 Using category's parent relationship\n$category-\u003eparent()-\u003eassociate($parent)-\u003esave();\n\n// #6 Using the parent attribute\n$category-\u003eparent_id = $parent-\u003egetKey();\n$category-\u003esave();\n\n// #7 Using static method\napp('rinvex.categories.category')-\u003ecreate($attributes, $parent);\n```\n\nAnd only a couple ways to prepend:\n\n```php\n// #1 Using deferred insert\n$category-\u003eprependToNode($parent)-\u003esave();\n\n// #2 Using parent category\n$parent-\u003eprependNode($category);\n```\n\n#### Inserting before or after specified category\n\nYou can make `$category` to be a neighbor of the `$neighbor` category.\nSuppose that `$neighbor` is some existing category, while target category can be fresh.\nIf target category exists, it will be moved to the new position and parent will be changed if it's required.\n\n```php\n# Explicit save\n$category-\u003eafterNode($neighbor)-\u003esave();\n$category-\u003ebeforeNode($neighbor)-\u003esave();\n\n# Implicit save\n$category-\u003einsertAfterNode($neighbor);\n$category-\u003einsertBeforeNode($neighbor);\n```\n\n#### Building a tree from array\n\nWhen using static method `create` on category, it checks whether attributes contains `children` key.\nIf it does, it creates more categories recursively, as follows:\n\n```php\n$category = app('rinvex.categories.category')-\u003ecreate([\n    'name' =\u003e [\n        'en' =\u003e 'New Category Title',\n    ],\n\n    'children' =\u003e [\n        [\n            'name' =\u003e 'Bar',\n\n            'children' =\u003e [\n                [ 'name' =\u003e 'Baz' ],\n            ],\n        ],\n    ],\n]);\n```\n\n`$category-\u003echildren` now contains a list of created child categories.\n\n#### Rebuilding a tree from array\n\nYou can easily rebuild a tree. This is useful for mass-changing the structure of the tree.\nGiven the `$data` as an array of categories, you can build the tree as follows:\n\n```php\n$data = [\n    [ 'id' =\u003e 1, 'name' =\u003e 'foo', 'children' =\u003e [ ... ] ],\n    [ 'name' =\u003e 'bar' ],\n];\n\napp('rinvex.categories.category')-\u003erebuildTree($data, $delete);\n```\n\nThere is an id specified for category with the title of `foo` which means that existing\ncategory will be filled and saved. If category does not exists `ModelNotFoundException` is\nthrown. Also, this category has `children` specified which is also an array of categories;\nthey will be processed in the same manner and saved as children of category `foo`.\n\nCategory `bar` has no primary key specified, so it will treated as a new one, and be created.\n\n`$delete` shows whether to delete categories that are already exists but not present\nin `$data`. By default, categories aren't deleted.\n\n### Retrieving categories\n\n_In some cases we will use an `$id` variable which is an id of the target category._\n\n#### Ancestors\n\nAncestors make a chain of parents to the category.\nHelpful for displaying breadcrumbs to the current category.\n\n```php\n// #1 Using accessor\n$result = $category-\u003egetAncestors();\n\n// #2 Using a query\n$result = $category-\u003eancestors()-\u003eget();\n\n// #3 Getting ancestors by primary key\n$result = app('rinvex.categories.category')-\u003eancestorsOf($id);\n```\n\n#### Descendants\n\nDescendants are all categories in a sub tree,\ni.e. children of category, children of children, etc.\n\n```php\n// #1 Using relationship\n$result = $category-\u003edescendants;\n\n// #2 Using a query\n$result = $category-\u003edescendants()-\u003eget();\n\n// #3 Getting descendants by primary key\n$result = app('rinvex.categories.category')-\u003edescendantsOf($id);\n\n// #3 Get descendants and the category by id\n$result = app('rinvex.categories.category')-\u003edescendantsAndSelf($id);\n```\n\nDescendants can be eagerly loaded:\n\n```php\n$categories = app('rinvex.categories.category')-\u003ewith('descendants')-\u003ewhereIn('id', $idList)-\u003eget();\n```\n\n#### Siblings\n\nSiblings are categories that have same parent.\n\n```php\n$result = $category-\u003egetSiblings();\n\n$result = $category-\u003esiblings()-\u003eget();\n```\n\nTo get only next siblings:\n\n```php\n// Get a sibling that is immediately after the category\n$result = $category-\u003egetNextSibling();\n\n// Get all siblings that are after the category\n$result = $category-\u003egetNextSiblings();\n\n// Get all siblings using a query\n$result = $category-\u003enextSiblings()-\u003eget();\n```\n\nTo get previous siblings:\n\n```php\n// Get a sibling that is immediately before the category\n$result = $category-\u003egetPrevSibling();\n\n// Get all siblings that are before the category\n$result = $category-\u003egetPrevSiblings();\n\n// Get all siblings using a query\n$result = $category-\u003eprevSiblings()-\u003eget();\n```\n\n#### Getting related models from other table\n\nImagine that each category `has many` products. I.e. `HasMany` relationship is established.\nHow can you get all products of `$category` and every its descendant? Easy!\n\n```php\n// Get ids of descendants\n$categories = $category-\u003edescendants()-\u003epluck('id');\n\n// Include the id of category itself\n$categories[] = $category-\u003egetKey();\n\n// Get products\n$goods = Product::whereIn('category_id', $categories)-\u003eget();\n```\n\nNow imagine that each category `has many` posts. I.e. `morphToMany` relationship is established this time.\nHow can you get all posts of `$category` and every its descendant? Is that even possible?! Sure!\n\n```php\n// Get ids of descendants\n$categories = $category-\u003edescendants()-\u003epluck('id');\n\n// Include the id of category itself\n$categories[] = $category-\u003egetKey();\n\n// Get posts\n$posts = \\App\\Models\\Post::withCategories($categories)-\u003eget();\n```\n\n#### Including category depth\n\nIf you need to know at which level the category is:\n\n```php\n$result = app('rinvex.categories.category')-\u003ewithDepth()-\u003efind($id);\n\n$depth = $result-\u003edepth;\n```\n\nRoot category will be at level 0. Children of root categories will have a level of 1, etc.\nTo get categories of specified level, you can apply `having` constraint:\n\n```php\n$result = app('rinvex.categories.category')-\u003ewithDepth()-\u003ehaving('depth', '=', 1)-\u003eget();\n```\n\n#### Default order\n\nEach category has it's own unique `_lft` value that determines its position in the tree.\nIf you want category to be ordered by this value, you can use `defaultOrder` method\non the query builder:\n\n```php\n// All categories will now be ordered by lft value\n$result = app('rinvex.categories.category')-\u003edefaultOrder()-\u003eget();\n```\n\nYou can get categories in reversed order:\n\n```php\n$result = app('rinvex.categories.category')-\u003ereversed()-\u003eget();\n```\n\n##### Shifting a category\n\nTo shift category up or down inside parent to affect default order:\n\n```php\n$bool = $category-\u003edown();\n$bool = $category-\u003eup();\n\n// Shift category by 3 siblings\n$bool = $category-\u003edown(3);\n```\n\nThe result of the operation is boolean value of whether the category has changed its position.\n\n#### Constraints\n\nVarious constraints that can be applied to the query builder:\n\n- **whereIsRoot()** to get only root categories;\n- **whereIsAfter($id)** to get every category (not just siblings) that are after a category with specified id;\n- **whereIsBefore($id)** to get every category that is before a category with specified id.\n\nDescendants constraints:\n\n```php\n$result = app('rinvex.categories.category')-\u003ewhereDescendantOf($category)-\u003eget();\n$result = app('rinvex.categories.category')-\u003ewhereNotDescendantOf($category)-\u003eget();\n$result = app('rinvex.categories.category')-\u003eorWhereDescendantOf($category)-\u003eget();\n$result = app('rinvex.categories.category')-\u003eorWhereNotDescendantOf($category)-\u003eget();\n\n// Include target category into result set\n$result = app('rinvex.categories.category')-\u003ewhereDescendantOrSelf($category)-\u003eget();\n```\n\nAncestor constraints:\n\n```php\n$result = app('rinvex.categories.category')-\u003ewhereAncestorOf($category)-\u003eget();\n```\n\n`$category` can be either a primary key of the model or model instance.\n\n#### Building a tree\n\nAfter getting a set of categories, you can convert it to tree. For example:\n\n```php\n$tree = app('rinvex.categories.category')-\u003eget()-\u003etoTree();\n```\n\nThis will fill `parent` and `children` relationships on every category in the set and\nyou can render a tree using recursive algorithm:\n\n```php\n$categories = app('rinvex.categories.category')-\u003eget()-\u003etoTree();\n\n$traverse = function ($categories, $prefix = '-') use (\u0026$traverse) {\n    foreach ($categories as $category) {\n        echo PHP_EOL.$prefix.' '.$category-\u003ename;\n\n        $traverse($category-\u003echildren, $prefix.'-');\n    }\n};\n\n$traverse($categories);\n```\n\nThis will output something like this:\n\n```\n- Root\n-- Child 1\n--- Sub child 1\n-- Child 2\n- Another root\n```\n\n##### Building flat tree\n\nAlso, you can build a flat tree: a list of categories where child categories are immediately\nafter parent category. This is helpful when you get categories with custom order\n(i.e. alphabetically) and don't want to use recursion to iterate over your categories.\n\n```php\n$categories = app('rinvex.categories.category')-\u003eget()-\u003etoFlatTree();\n```\n\n##### Getting a subtree\n\nSometimes you don't need whole tree to be loaded and just some subtree of specific category:\n\n```php\n$root = app('rinvex.categories.category')-\u003efind($rootId);\n$tree = $root-\u003edescendants-\u003etoTree($root);\n```\n\nNow `$tree` contains children of `$root` category.\n\nIf you don't need `$root` category itself, do following instead:\n\n```php\n$tree = app('rinvex.categories.category')-\u003edescendantsOf($rootId)-\u003etoTree($rootId);\n```\n\n### Deleting categories\n\nTo delete a category:\n\n```php\n$category-\u003edelete();\n```\n\n**IMPORTANT!** Any descendant that category has will also be **deleted**!\n\n**IMPORTANT!** Categories are required to be deleted as models, **don't** try do delete them using a query like so:\n\n```php\napp('rinvex.categories.category')-\u003ewhere('id', '=', $id)-\u003edelete();\n```\n\n**That will break the tree!**\n\n\n### Helper methods\n\n```php\n// Check if category is a descendant of other category\n$bool = $category-\u003eisDescendantOf($parent);\n\n// Check whether the category is a root:\n$bool = $category-\u003eisRoot();\n\n// Other checks\n$category-\u003eisChildOf($other);\n$category-\u003eisAncestorOf($other);\n$category-\u003eisSiblingOf($other);\n```\n\n### Checking consistency\n\nYou can check whether a tree is broken (i.e. has some structural errors):\n\n```php\n// Check if tree is broken\n$bool = app('rinvex.categories.category')-\u003eisBroken();\n\n// Get tree error statistics\n$data = app('rinvex.categories.category')-\u003ecountErrors();\n```\n\nTree error statistics will return an array with following keys:\n\n- `oddness` -- the number of categories that have wrong set of `lft` and `rgt` values\n- `duplicates` -- the number of categories that have same `lft` or `rgt` values\n- `wrong_parent` -- the number of categories that have invalid `parent_id` value that doesn't correspond to `lft` and `rgt` values\n- `missing_parent` -- the number of categories that have `parent_id` pointing to category that doesn't exists\n\n#### Fixing tree\n\nCategory tree can now be fixed if broken. Using inheritance info from `parent_id` column,\nproper `_lft` and `_rgt` values are set for every category.\n\n```php\napp('rinvex.categories.category')-\u003efixTree();\n```\n\n\u003e **Note:** Check **[Nested Sets](https://github.com/lazychaser/laravel-nestedset)** package for further details.\n\n\n## Changelog\n\nRefer to the [Changelog](CHANGELOG.md) for a full history of the project.\n\n\n## Support\n\nThe following support channels are available at your fingertips:\n\n- [Chat on Slack](https://bit.ly/rinvex-slack)\n- [Help on Email](mailto:help@rinvex.com)\n- [Follow on Twitter](https://twitter.com/rinvex)\n\n\n## Contributing \u0026 Protocols\n\nThank you for considering contributing to this project! The contribution guide can be found in [CONTRIBUTING.md](CONTRIBUTING.md).\n\nBug reports, feature requests, and pull requests are very welcome.\n\n- [Versioning](CONTRIBUTING.md#versioning)\n- [Pull Requests](CONTRIBUTING.md#pull-requests)\n- [Coding Standards](CONTRIBUTING.md#coding-standards)\n- [Feature Requests](CONTRIBUTING.md#feature-requests)\n- [Git Flow](CONTRIBUTING.md#git-flow)\n\n\n## Security Vulnerabilities\n\nWe want to ensure that this package is secure for everyone. If you've discovered a security vulnerability in this package, we appreciate your help in disclosing it to us in a [responsible manner](https://en.wikipedia.org/wiki/Responsible_disclosure).\n\nPublicly disclosing a vulnerability can put the entire community at risk. If you've discovered a security concern, please email us at [help@rinvex.com](mailto:help@rinvex.com). We'll work with you to make sure that we understand the scope of the issue, and that we fully address your concern. We consider correspondence sent to [help@rinvex.com](mailto:help@rinvex.com) our highest priority, and work to address any issues that arise as quickly as possible.\n\nAfter a security vulnerability has been corrected, a security hotfix release will be deployed as soon as possible.\n\n\n## About Rinvex\n\nRinvex is a software solutions startup, specialized in integrated enterprise solutions for SMEs established in Alexandria, Egypt since June 2016. We believe that our drive The Value, The Reach, and The Impact is what differentiates us and unleash the endless possibilities of our philosophy through the power of software. We like to call it Innovation At The Speed Of Life. That’s how we do our share of advancing humanity.\n\n\n## License\n\nThis software is released under [The MIT License (MIT)](LICENSE).\n\n(c) 2016-2022 Rinvex LLC, Some rights reserved.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frinvex%2Flaravel-categories","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frinvex%2Flaravel-categories","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frinvex%2Flaravel-categories/lists"}