Taggable

Taggable

Model Taggable Management.

Moamen Eltouny (Raggi)
PHP Version : >= 7.2 Laravel Version : >= 6.0 License Support
Source Packagist Version Packagist Downloads

Install

Install the latest version using Composer

composer require pharaonic/laravel-taggable
php artisan migrate

OptionalPublish the config & migrations.

php artisan vendor:publish --tag=laravel-taggable
Tag Model

Depends on Translatable.

You can create your tag or manipulate it.

use Pharaonic\Laravel\Taggable\Models\Tag;

$tag = Tag::create();
$tag->translateOrNew('en')->name = 'First Tag';
$tag->save();

Incuding Taggable into Model.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Pharaonic\Laravel\Taggable\Traits\Taggable;

class Article extends Model
{
    use Taggable;
    ...
}
Methods

tag ($tags)

You can use any of this ways to assign a tag to the model.

$article->tag(1, 2);            // with Tags IDs
$article->tag([1, 2]);          // with Array of Tags IDs

$article->tag(Tag::all());      // with Eloquent Collection of Tags

$article->tag($tag1, $tag2);    // with Models
$article->tag([$tag1, $tag2]);  // with Array of Models

detag ($tags)

You can use any of this ways to detach a model from tags.

$article->detag(1, 2);         // with Tags IDs
$article->detag([1, 2]);       // with Array of Tags IDs

$article->detag(Tag::all());      // with Eloquent Collection of Tags

$article->detag($tag1, $tag2);       // with Models
$article->detag([$tag1, $tag2]);     // with Array of Models

syncTags ($tags)

You can use any of this ways to detach a model from all unnecessary tags
and attach/keep it to all necessary tags.

$article->syncTags(1, 3);         // with Tags IDs
$article->syncTags([1, 3]);       // with Array of Tags IDs

$article->syncTags(Tag::whereIn('id', [1, 3])->get());      // with Eloquent Collection of Tags

$article->syncTags($tag1, $tag3);       // with Models
$article->syncTags([$tag1, $tag3]);     // with Array of Models
Relationships

tags

Getting all tags (Parents).

dump($article->tags);

// Returns Illuminate\Database\Eloquent\Collection
Scopes

Popularity

Getting all tags sorted by popularity.

dump(Tag::popular()->get());
// Returns Illuminate\Database\Eloquent\Collection
Tag Children

Config File

You have to assign your relationships here like articles in config/Pharaonic/taggable.php.

return [

    /**
        *      Get all of the models are assined a specific Tag
        *               Getting Tag children
        */
    
    'children' => [
        'articles'      => App\Models\Article::class,
    ]

];

Then you can get the tag children like products.

dump($tag->articles);
// Returns Illuminate\Database\Eloquent\Collection