Category Model
Hierarchical category system for organizing products and other entities.
Overview
The Category model provides a flexible, hierarchical system for organizing products and other categorizable entities. It supports parent-child relationships, metadata, and is used in conjunction with the Categorizable model for polymorphic categorization.
Attributes
| Attribute | Type | Description |
|---|---|---|
id | int | Primary key |
uuid | string | Unique identifier for routing |
name | string | Category name |
description | string | Category description |
slug | string | URL-friendly identifier |
image_url | string | Category image URL |
is_active | boolean | Active status flag |
display_order | int | Display order |
metadata | json | Additional JSON data |
created_at | timestamp | Creation timestamp |
updated_at | timestamp | Last update timestamp |
Relationships
Belongs To
belongsTo(Category)- Parent category
Has Many
hasMany(Category)- Child categories
Belongs To Many
belongsToMany(Product)- Categorized products (via Categorizable)
Key Features
Hierarchical Structure
- Parent-child category relationships
- Unlimited nesting
- Flexible category trees
Metadata & Customization
- Store additional data as JSON
- Custom display order
- Category images and branding
Active/Inactive Status
- Easily enable or disable categories
- Filter by active status
Routing & Slugs
- URL-friendly slugs for SEO
- Route key using UUID
Usage Examples
Creating a Category
php
$category = Category::create([
'uuid' => Str::uuid(),
'name' => 'Pain Relief',
'description' => 'Medications for pain management',
'slug' => 'pain-relief',
'is_active' => true,
'display_order' => 1,
'metadata' => [
'icon' => 'pain-relief-icon',
'color' => '#FF5733'
]
]);Getting Associated Data
php
// Get child categories
$children = $category->children;
// Get parent category
$parent = $category->parent;
// Get categorized products
$products = $category->products;Scopes
Active Categories
php
// Get only active categories
Category::where('is_active', true)->get();Route Key
The Category model uses the uuid as the route key for secure routing:
php
// Route model binding uses UUID
Route::get('/categories/{category}', function (Category $category) {
return $category;
});Related Models
- Product - Categorized products
- Categorizable - Categorization relationships