veiliglanceren/laravel-morph-categories
最新稳定版本:2.0.2
Composer 安装命令:
composer require veiliglanceren/laravel-morph-categories
包简介
A Laravel package to support polymorphic category relationships for any model.
README 文档
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 = 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.
统计信息
- 总下载量: 655
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 0
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-07-21