Skip to content

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

AttributeTypeDescription
idintPrimary key
uuidstringUnique identifier for routing
namestringCategory name
descriptionstringCategory description
slugstringURL-friendly identifier
image_urlstringCategory image URL
is_activebooleanActive status flag
display_orderintDisplay order
metadatajsonAdditional JSON data
created_attimestampCreation timestamp
updated_attimestampLast 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;
});