### Install angkor/laravel-categories via Composer Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Install the package via Composer. ```shell composer require angkor/laravel-categories ``` -------------------------------- ### Example tree output Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Example output of the recursive tree rendering, showing categories with prefixes indicating depth. ```text - Root -- Child 1 --- Sub child 1 -- Child 2 - Another root ``` -------------------------------- ### Retrieve categories and model categories Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Shows how to retrieve all categories, get a model instance, and access the attached categories as a collection or query builder. ```php // Get all categories $allCategories = app('angkor.categories.category')->all(); // Get instance of your model $post = \App\Models\Post::find(123); // Get attached categories collection $post->categories; // Get attached categories query builder $post->categories(); ``` -------------------------------- ### Get categories in reversed order Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Get categories in reversed default order. ```php $result = app('angkor.categories.category')->reversed()->get(); ``` -------------------------------- ### Get products of category and descendants Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Get all products belonging to a category and its descendants when a HasMany relationship is established. Collect descendant IDs, include the category's own ID, then query the Product model. ```php // Get ids of descendants $categories = $category->descendants()->pluck('id'); // Include the id of category itself $categories[] = $category->getKey(); // Get products $goods = Product::whereIn('category_id', $categories)->get(); ``` -------------------------------- ### Create category with custom slug Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Creates a category with explicit slug and name translations. Slugs are auto-generated if not provided, but this example passes a custom slug. ```php app('angkor.categories.category')->create(['name' => ['en' => 'My New Category'], 'slug' => 'custom-category-slug']); ``` -------------------------------- ### Use withAnyCategories scope with various inputs Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Shows all accepted input types for the `withAnyCategories()` scope: single ID, array/collection of IDs, model instance, slug, array/collection of slugs, and collection of model instances. The scope returns a query builder, so you can chain or call `get()`. ```php // Single category id $post->withAnyCategories(1)->get(); // Multiple category IDs array $post->withAnyCategories([1, 2, 5])->get(); // Multiple category IDs collection $post->withAnyCategories(collect([1, 2, 5]))->get(); // Single category model instance $categoryInstance = app('angkor.categories.category')->first(); $post->withAnyCategories($categoryInstance)->get(); // Single category slug $post->withAnyCategories('test-category')->get(); // Multiple category slugs array $post->withAnyCategories(['first-category', 'second-category'])->get(); // Multiple category slugs collection $post->withAnyCategories(collect(['first-category', 'second-category']))->get(); // Multiple category model instances $categoryInstances = app('angkor.categories.category')->whereIn('id', [1, 2, 5])->get(); $post->withAnyCategories($categoryInstances)->get(); ``` -------------------------------- ### Get categories at specified depth Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Get categories at a specific depth level by applying a having constraint on the depth column. ```php $result = app('angkor.categories.category')->withDepth()->having('depth', '=', 1)->get(); ``` -------------------------------- ### Get previous siblings Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Retrieve the previous sibling (immediately before) or all siblings before the category. The prevSiblings() method returns a query builder. ```php // Get a sibling that is immediately before the category $result = $category->getPrevSibling(); // Get all siblings that are before the category $result = $category->getPrevSiblings(); // Get all siblings using a query $result = $category->prevSiblings()->get(); ``` -------------------------------- ### Render category tree recursively Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Renders a category tree using a recursive closure that prints each category name with a prefix indicating depth. The output is similar to the example shown below. ```php $categories = app('angkor.categories.category')->get()->toTree(); $traverse = function ($categories, $prefix = '-') use (&$traverse) { foreach ($categories as $category) { echo PHP_EOL.$prefix.' '.$category->name; $traverse($category->children, $prefix.'-'); } }; $traverse($categories); ``` -------------------------------- ### Get next siblings Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Retrieve the next sibling (immediately after) or all siblings after the category. The nextSiblings() method returns a query builder. ```php // Get a sibling that is immediately after the category $result = $category->getNextSibling(); // Get all siblings that are after the category $result = $category->getNextSiblings(); // Get all siblings using a query $result = $category->nextSiblings()->get(); ``` -------------------------------- ### Get posts of category and descendants Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Get all posts belonging to a category and its descendants when a morphToMany relationship is established. Uses the withCategories scope on the Post model. ```php // Get ids of descendants $categories = $category->descendants()->pluck('id'); // Include the id of category itself $categories[] = $category->getKey(); // Get posts $posts = \App\Models\Post::withCategories($categories)->get(); ``` -------------------------------- ### Get subtree of a category Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Gets a subtree of a specific category. `$tree` contains the children of the `$root` category. ```php $root = app('angkor.categories.category')->find($rootId); $tree = $root->descendants->toTree($root); ``` -------------------------------- ### Get siblings of a category Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Get all sibling categories (categories with the same parent) using either the getSiblings method or the siblings relationship query. ```php $result = $category->getSiblings(); $result = $category->siblings()->get(); ``` -------------------------------- ### Get subtree excluding root Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Gets a subtree without including the root category itself, using `descendantsOf` and `toTree`. ```php $tree = app('angkor.categories.category')->descendantsOf($rootId)->toTree($rootId); ``` -------------------------------- ### Get category with depth Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Retrieve a category with its depth level. Root categories are at level 0, children of root at level 1, etc. ```php $result = app('angkor.categories.category')->withDepth()->find($id); $depth = $result->depth; ``` -------------------------------- ### Apply ancestor constraint Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Apply an ancestor constraint to get categories that are ancestors of the given category. The $category can be a primary key or a model instance. ```php $result = app('angkor.categories.category')->whereAncestorOf($category)->get(); ``` -------------------------------- ### Get descendants of a category Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Retrieve all descendant categories of a category using the relationship, a query, or by primary key. The descendantsAndSelf method includes the category itself. ```php // #1 Using relationship $result = $category->descendants; // #2 Using a query $result = $category->descendants()->get(); // #3 Getting descendants by primary key $result = app('angkor.categories.category')->descendantsOf($id); // #3 Get descendants and the category by id $result = app('angkor.categories.category')->descendantsAndSelf($id); ``` -------------------------------- ### Get all models attached to a category Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Retrieves all models of a given class attached to a category. The `entries()` method accepts the model class name and returns a query builder. ```php $category = app('angkor.categories.category')->find(1); $category->entries(\App\Models\Post::class)->get(); ``` -------------------------------- ### Get category ancestors Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Retrieves the ancestor chain of a category, useful for breadcrumbs. Three methods are shown: accessor, query builder, and static method by primary key. ```php // #1 Using accessor $result = $category->getAncestors(); // #2 Using a query $result = $category->ancestors()->get(); // #3 Getting ancestors by primary key $result = app('angkor.categories.category')->ancestorsOf($id); ``` -------------------------------- ### Run angkor categories migrations Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Run the package's migrations. ```shell php artisan angkor:migrate:categories ``` -------------------------------- ### Publish angkor categories resources Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Publish the package's migrations and config files. ```shell php artisan angkor:publish:categories ``` -------------------------------- ### Build tree from array with create() Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Builds a category tree from an array. The create() method recursively creates child categories when the 'children' key is present. The resulting $category->children contains the created child categories. ```php $category = app('angkor.categories.category')->create([ 'name' => [ 'en' => 'New Category Title', ], 'children' => [ [ 'name' => 'Bar', 'children' => [ [ 'name' => 'Baz' ], ], ], ], ]); ``` -------------------------------- ### Create a root category Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Creates a new category as a root node. Both create() and fill()->save() append the category to the end of the tree. ```php app('angkor.categories.category')->create($attributes); // Saved as root $category = app('angkor.categories.category')->fill($attributes); $category->save(); // Saved as root ``` -------------------------------- ### Build flat tree with toFlatTree() Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Builds a flat tree: a list of categories where child categories appear immediately after their parent. Useful when categories have a custom order (e.g., alphabetical) and recursion is not desired. ```php $categories = app('angkor.categories.category')->get()->toFlatTree(); ``` -------------------------------- ### Convert categories to tree with toTree() Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Converts a set of categories into a tree structure, filling the `parent` and `children` relationships on every category in the set. ```php $tree = app('angkor.categories.category')->get()->toTree(); ``` -------------------------------- ### Prepend category to parent Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Prepends a category as the first child of a given parent. Two equivalent methods are shown. ```php // #1 Using deferred insert $category->prependToNode($parent)->save(); // #2 Using parent category $parent->prependNode($category); ``` -------------------------------- ### Check tree consistency with isBroken() and countErrors() Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Checks whether the tree is broken and retrieves error statistics. `countErrors` returns an array with keys `oddness`, `duplicates`, `wrong_parent`, and `missing_parent`. ```php // Check if tree is broken $bool = app('angkor.categories.category')->isBroken(); // Get tree error statistics $data = app('angkor.categories.category')->countErrors(); ``` -------------------------------- ### Rebuild tree with rebuildTree() Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Rebuilds the entire tree from an array. Categories with an 'id' are updated (throws ModelNotFoundException if not found), those without are created. The $delete flag controls whether existing categories not in $data are deleted (default false). ```php $data = [ [ 'id' => 1, 'name' => 'foo', 'children' => [ ... ] ], [ 'name' => 'bar' ], ]; app('angkor.categories.category')->rebuildTree($data, $delete); ``` -------------------------------- ### Make existing category a root Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Makes an existing category a root node. saveAsRoot() implicitly saves, while makeRoot()->save() requires an explicit save. The category is appended to the end of the tree. ```php // #1 Implicit save $category->saveAsRoot(); // #2 Explicit save $category->makeRoot()->save(); ``` -------------------------------- ### Category relationship helper methods Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Helper methods to check relationships between categories: `isDescendantOf`, `isRoot`, `isChildOf`, `isAncestorOf`, and `isSiblingOf`. ```php // Check if category is a descendant of other category $bool = $category->isDescendantOf($parent); // Check whether the category is a root: $bool = $category->isRoot(); // Other checks $category->isChildOf($other); $category->isAncestorOf($other); $category->isSiblingOf($other); ``` -------------------------------- ### Insert category before or after neighbor Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Inserts a category before or after an existing neighbor category. If the target category exists, it is moved to the new position and its parent is updated if necessary. ```php # Explicit save $category->afterNode($neighbor)->save(); $category->beforeNode($neighbor)->save(); # Implicit save $category->insertAfterNode($neighbor); $category->insertBeforeNode($neighbor); ``` -------------------------------- ### Order categories by default order Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Order categories by their unique _lft value, which determines their position in the tree. ```php // All categories will now be ordered by lft value $result = app('angkor.categories.category')->defaultOrder()->get(); ``` -------------------------------- ### Check if model has any categories with hasAnyCategories() Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Checks if any of the given categories are attached to the model using hasAnyCategories(). Accepts the same input types as attachCategories() and returns a boolean. The hasAllCategories() method uses the same signature but performs a strict check for all categories. ```php // Single category id $post->hasAnyCategories(1); // Multiple category IDs array $post->hasAnyCategories([1, 2, 5]); // Multiple category IDs collection $post->hasAnyCategories(collect([1, 2, 5])); // Single category model instance $categoryInstance = app('angkor.categories.category')->first(); $post->hasAnyCategories($categoryInstance); // Single category slug $post->hasAnyCategories('test-category'); // Multiple category slugs array $post->hasAnyCategories(['first-category', 'second-category']); // Multiple category slugs collection $post->hasAnyCategories(collect(['first-category', 'second-category'])); // Multiple category model instances $categoryInstances = app('angkor.categories.category')->whereIn('id', [1, 2, 5])->get(); $post->hasAnyCategories($categoryInstances); ``` -------------------------------- ### Attach categories with attachCategories() Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Attaches categories to a model using the attachCategories() method. Accepts a single ID, array, collection, model instance, slug, or multiple model instances. Does not touch currently attached categories; use syncCategories() to detach records not in the given items. ```php // Single category id $post->attachCategories(1); // Multiple category IDs array $post->attachCategories([1, 2, 5]); // Multiple category IDs collection $post->attachCategories(collect([1, 2, 5])); // Single category model instance $categoryInstance = app('angkor.categories.category')->first(); $post->attachCategories($categoryInstance); // Single category slug $post->attachCategories('test-category'); // Multiple category slugs array $post->attachCategories(['first-category', 'second-category']); // Multiple category slugs collection $post->attachCategories(collect(['first-category', 'second-category'])); // Multiple category model instances $categoryInstances = app('angkor.categories.category')->whereIn('id', [1, 2, 5])->get(); $post->attachCategories($categoryInstances); ``` -------------------------------- ### Eager load descendants Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Eager load the descendants relationship for multiple categories to avoid N+1 queries. ```php $categories = app('angkor.categories.category')->with('descendants')->whereIn('id', $idList)->get(); ``` -------------------------------- ### Apply descendant constraints Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Apply descendant constraints to the query builder. The whereDescendantOrSelf method includes the target category in the result set. ```php $result = app('angkor.categories.category')->whereDescendantOf($category)->get(); $result = app('angkor.categories.category')->whereNotDescendantOf($category)->get(); $result = app('angkor.categories.category')->orWhereDescendantOf($category)->get(); $result = app('angkor.categories.category')->orWhereNotDescendantOf($category)->get(); // Include target category into result set $result = app('angkor.categories.category')->whereDescendantOrSelf($category)->get(); ``` -------------------------------- ### Use Categorizable trait in Eloquent model Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Adds category support to an Eloquent model by using the Categorizable trait. Import the trait and include it in the model class. ```php use Angkor\Categories\Traits\Categorizable; class Post extends Model { use Categorizable; // ... } ``` -------------------------------- ### Fix broken tree with fixTree() Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Fixes a broken category tree by setting proper `_lft` and `_rgt` values based on the `parent_id` column. ```php app('angkor.categories.category')->fixTree(); ``` -------------------------------- ### Append category to parent Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Appends a category as the last child of a given parent. Provides multiple approaches: deferred insert, parent methods, relationships, and static create. ```php // #1 Using deferred insert $category->appendToNode($parent)->save(); // #2 Using parent category $parent->appendNode($category); // #3 Using parent's children relationship $parent->children()->create($attributes); // #5 Using category's parent relationship $category->parent()->associate($parent)->save(); // #6 Using the parent attribute $category->parent_id = $parent->getKey(); $category->save(); // #7 Using static method app('angkor.categories.category')->create($attributes, $parent); ``` -------------------------------- ### Shift category up or down Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Shift a category up or down within its parent to affect default order. The methods return a boolean indicating whether the position changed. ```php $bool = $category->down(); $bool = $category->up(); // Shift category by 3 siblings $bool = $category->down(3); ``` -------------------------------- ### Manage category translations Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Manages category translations: updating a single translation with `setTranslation()`, updating multiple via Eloquent `update()`, retrieving a single translation with `getTranslation()`, all translations with `getTranslations()`, and accessing the default locale title directly. ```php $category = app('angkor.categories.category')->find(1); // Update title translations $category->setTranslation('name', 'en', 'New English Category Title')->save(); // Alternatively you can use default eloquent update $category->update([ 'name' => [ 'en' => 'New Category', 'ar' => 'تصنيف جديد', ], ]); // Get single category translation $category->getTranslation('name', 'en'); // Get all category translations $category->getTranslations('name'); // Get category title in default locale $category->name; ``` -------------------------------- ### Incorrect category deletion (breaks tree) Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Incorrect way to delete a category using a query. This will break the tree; categories must be deleted as models. ```php app('angkor.categories.category')->where('id', '=', $id)->delete(); ``` -------------------------------- ### Delete a category Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Deletes a category. IMPORTANT: Any descendant of that category will also be deleted. ```php $category->delete(); ``` -------------------------------- ### Check if category moved with hasMoved() Source: https://github.com/angkordotdev/laravel-categories/blob/main/README.md Checks whether a category actually moved after a save operation. The save() method returns a boolean, and hasMoved() indicates if the structural position changed. ```php if ($category->save()) { $moved = $category->hasMoved(); } ```