veiliglanceren / laravel-morph-categories
A Laravel package to support polymorphic category relationships for any model.
1.0.0
2025-07-21 22:29 UTC
Requires
- php: ^8.1
- ext-dom: *
- ext-simplexml: *
- laravel/framework: ^10.0|^11.0|^12.0
- spatie/laravel-sluggable: ^2.0|^3.0
Requires (Dev)
- orchestra/testbench: ^8.0 || ^9.0 || ^10.0
- pestphp/pest: ^2.0 || ^3.0
- pestphp/pest-plugin-laravel: ^2.0 || ^3.0
This package is not auto-updated.
Last update: 2025-07-22 01:52:32 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
๐ฆ 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 = Category::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
๐ Relationships
$post->categories; // Collection of Category models $category->categoryables; // 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.