A package to make eloquent model taggable

v0.1-beta 2018-06-23 19:36 UTC

This package is not auto-updated.

Last update: 2022-05-23 16:23:31 UTC


This Package is used to make eloquent model taggable. It can be used in laravel 5.5 or higher.


composer require zaichaopan/taggable


  • Add tags and taggables table

After you install the package, run migration command to add tags and taggables table

php artisan migrate

The schemas of these two tables

// tags table
Schema::create('tags', function (Blueprint $table) {
// taggables table
Schema::create('taggables', function (Blueprint $table) {

This packages also provides Tag and Taggable models.

// To add a create tag
use  Zaichaopan\Taggable\Models\Tag;

Tag::create(['name' => 'laravel']);

// To get all the tag names
$names = Tag::getNames();


Please make sure tag name is unique. After you create or update a tag, its slug value will be automatically added or updated based on its name value.

  • Add hasTags trait to the model you want to tag.

Let's say you have Activity model and you can give it tag.

use Zaichaopan\Taggable\Traits\HasTags;

class Activity extends Model
    use HasTags;

The hasTags trait provides the following methods to the model which uses it


It is used to get all the tags of the model:

$tags = $activity->tags;


 * @param string|array ...$tagNames
public function tag(...$tagNames): void

// or
$activity->tag('outdoor', 'sports');

// or
$activity->tag(['outdoor', 'sports']);


The tag name provided must be valid (exists in the tags table). If a tag name is invalid, it will be ignored. If a tag has already been given to a model, it will not be given again.


 * @param string|array ...$tagNames
public function reTag(...$tagNames): void

It is used to update a model's tag. After calling this method on a model, all its old tags will be moved and only the new tag will remain. If the tag name provided is invalid, it will be ignored. If all the provided tag names are invalid, the model will not be retagged. It will still keep its old tags.


// the tag of the activity will be sports

// or
$activity->reTag(['outdoor', 'sports']);


 * @param string|array ...$tagNames
public function unTag(...$tagNames): void

It is used to remove a tag or multiple tags from a model. If a given tag name is invalid, it will be ignore. If all the given tag names are invalid, none of the model's tags will be removed.


// or
$activity->unTag('outdoor', 'sports');

// or
$activity->unTag(['outdoor', 'sports']);


public function unTagAll(): void

It is used to removed all the tags of the model.