A Laravel package to add polymorphic category support to any model. Easily attach, detach, sync, and query categories using elegant Eloquent relationships.
composer require veiliglanceren/laravel-morph-categories
use VeiligLanceren\LaravelMorphCategories\Traits\HasCategory;
class Post extends Model
{
use HasCategory;
}
$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
- Rename tables if you already use
categories
for something else. - Replace the model class with your own
Category
orCategoryable
implementation.
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,
],
];
$post->morphCategories; // Collection of MorphCategory models
$category->morphCategoryables; // MorphToMany to all related models
You can query models with specific categories:
Post::withCategory('news')->get();
Post::withCategory($category)->get();
This package uses Pest and Orchestra Testbench:
composer test
Or manually:
vendor/bin/pest
The MIT License (MIT). Please see License File for more information.
Developed and maintained by Niels Hamelink at VeiligLanceren.nl.