LaravelPackages.net
Acme Inc.
Toggle sidebar
veiliglanceren/laravel-morph-categories

A Laravel package to support polymorphic category relationships for any model.

683
1
2.0.2
About veiliglanceren/laravel-morph-categories

veiliglanceren/laravel-morph-categories is a Laravel package for a laravel package to support polymorphic category relationships for any model.. It currently has 1 GitHub stars and 683 downloads on Packagist (latest version 2.0.2). Install it with composer require veiliglanceren/laravel-morph-categories. Discover more Laravel packages by veiliglanceren or browse all Laravel packages to compare alternatives.

Last updated

Laravel Morph Category

Latest Version on Packagist Total Downloads

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 categories for something else.
  • Replace the model class with your own Category or Categoryable implementation.

βš™οΈ 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.

Comments