veiliglanceren / laravel-morph-categories
A Laravel package to support polymorphic category relationships for any model.
Package info
github.com/VeiligLanceren-nl/laravel-morph-categories
pkg:composer/veiliglanceren/laravel-morph-categories
Requires
- php: ^8.2
- ext-dom: *
- ext-simplexml: *
- laravel/framework: ^12.0|^13.0
- spatie/laravel-sluggable: ^3.0|^4.0
Requires (Dev)
- orchestra/testbench: ^10.0 || ^11.0
- pestphp/pest: ^3.0 || ^4.0 || ^5.0
- pestphp/pest-plugin-laravel: ^3.0 || ^4.0 || ^5.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is not auto-updated.
Last update: 2026-11-09 19:40:14 UTC
README
A Laravel package to add polymorphic category support to any model. Easily attach, detach, sync, and query categories using elegant Eloquent relationships.
๐ Installation
composer require veiliglanceren/laravel-morph-categories
Requirements
| Package version | PHP | Laravel |
|---|---|---|
| 3.x | 8.2 or newer | 12.x, 13.x |
| 2.x | 8.1 or newer | 10.x, 11.x, 12.x |
Upgrading to 3.0
Version 3.0 drops support for Laravel 10 and 11 and PHP 8.1, and adds support for Laravel 13. There are no API changes. If you are still on Laravel 10 or 11, stay on ^2.0.
๐ฆ Usage
1. Add Trait to Your Model
use VeiligLanceren\LaravelMorphCategories\Traits\HasCategory; class Post extends Model { use HasCategory; }
2. Attach, Detach & Sync Categories
$post = Post::find(1); $category = MorphCategory::create(['name' => 'News']); $post->attachCategory($category); $post->detachCategory($category); $post->syncCategories([$category->id]);
You can also use slugs or IDs:
$post->hasCategory('news'); // by slug $post->hasCategory($category); // by model $post->hasCategory($category->id); // by ID
โ Use Cases
- Rename tables if you already use
categoriesfor something else. - Replace the model class with your own
CategoryorCategoryableimplementation.
โ๏ธ Configuration
You can publish and customize the config file:
php artisan vendor:publish --tag=category-config
This will create a file at config/category.php with the following structure:
return [ 'tables' => [ 'categories' => 'categories', 'categoryables' => 'categoryables', ], 'models' => [ 'category' => \VeiligLanceren\LaravelMorphCategories\Models\MorphCategory::class, 'categoryable' => \VeiligLanceren\LaravelMorphCategories\Models\MorphCategoryable::class, ], ];
๐ Relationships
$post->morphCategories; // Collection of MorphCategory models $category->morphCategoryables; // MorphToMany to all related models
๐ Query Scoping
You can query models with specific categories:
Post::withCategory('news')->get(); Post::withCategory($category)->get();
๐งช Testing
This package uses Pest and Orchestra Testbench:
composer test
Or manually:
vendor/bin/pest
๐ License
The MIT License (MIT). Please see License File for more information.
๐ค Author
Developed and maintained by Niels Hamelink at VeiligLanceren.nl.