Skip to content

Categorizable Model

Polymorphic pivot table that connects any model to categories with specific categorization types.

Overview

The Categorizable model is a polymorphic pivot table that links any model (such as Product) to categories, supporting multiple categorization types (e.g., drug class, therapeutic category, brand group). It enables flexible, multi-dimensional categorization for products and other entities.

Attributes

AttributeTypeDescription
idintPrimary key
category_idintForeign key to Category
categorizable_typestringPolymorphic model type
categorizable_idintPolymorphic model ID
sort_orderintDisplay order
metadatajsonAdditional JSON data
created_attimestampCreation timestamp
updated_attimestampLast update timestamp

Relationships

Belongs To

  • belongsTo(Category) - Associated category

Morph To

  • morphTo() - Polymorphic relationship to categorizable models (e.g., Product)

Key Features

Polymorphic Relationships

  • Connects any model to categories
  • Supports multiple categorizable types (Product, etc.)
  • Enables flexible, multi-entity categorization

Categorization Types

  • Supports multiple categorization types per model
  • Examples: drug class, therapeutic category, dosage form, brand group

Metadata & Sorting

  • Store additional data as JSON
  • Custom sort order for display

Usage Examples

Creating a Categorizable Record

php
Categorizable::create([
    'category_id' => $category->id,
    'categorizable_type' => Product::class,
    'categorizable_id' => $product->id,
    'sort_order' => 1,
    'metadata' => [
        'prescription_required' => false
    ]
]);

Querying Categorizations

php
// Get all categorizations for a product
$categorizations = Categorizable::where('categorizable_type', Product::class)
    ->where('categorizable_id', $product->id)
    ->get();

// Get all products in a category for a specific type
$productIds = Categorizable::where('category_id', $category->id)
    ->pluck('categorizable_id');
$products = Product::whereIn('id', $productIds)->get();

Filtering by Type

php
// Get categorizations by type
$drugClassCategorizations = Categorizable::ofType('drug_class')->get();

Scopes

By Categorization Type

php
Categorizable::ofType('drug_class')->get();

By Categorizable Type

php
Categorizable::forCategorizable(Product::class)->get();

Ordered

php
Categorizable::ordered()->get();