Giter Club home page Giter Club logo

laravel-tags's Introduction

Add tags and taggable behaviour to a Laravel app

Latest Version on Packagist MIT Licensed GitHub Workflow Status Total Downloads

This package offers taggable behaviour for your models. After the package is installed the only thing you have to do is add the HasTags trait to an Eloquent model to make it taggable.

But we didn't stop with the regular tagging capabilities you find in every package. Laravel Tags comes with batteries included. Out of the box it has support for translating tags, multiple tag types and sorting capabilities.

You'll find the documentation on https://spatie.be/docs/laravel-tags.

Here are some code examples:

// apply HasTags trait to a model
use Illuminate\Database\Eloquent\Model;
use Spatie\Tags\HasTags;

class NewsItem extends Model
{
    use HasTags;
    
    // ...
}
// create a model with some tags
$newsItem = NewsItem::create([
   'name' => 'The Article Title',
   'tags' => ['first tag', 'second tag'], //tags will be created if they don't exist
]);

// attaching tags
$newsItem->attachTag('third tag');
$newsItem->attachTag('third tag','some_type');
$newsItem->attachTags(['fourth tag', 'fifth tag']);
$newsItem->attachTags(['fourth_tag','fifth_tag'],'some_type');

// detaching tags
$newsItem->detachTag('third tag');
$newsItem->detachTag('third tag','some_type');
$newsItem->detachTags(['fourth tag', 'fifth tag']);
$newsItem->detachTags(['fourth tag', 'fifth tag'],'some_type');

// get all tags of a model
$newsItem->tags;

// syncing tags
$newsItem->syncTags(['first tag', 'second tag']); // all other tags on this model will be detached

// syncing tags with a type
$newsItem->syncTagsWithType(['category 1', 'category 2'], 'categories'); 
$newsItem->syncTagsWithType(['topic 1', 'topic 2'], 'topics'); 

// retrieving tags with a type
$newsItem->tagsWithType('categories'); 
$newsItem->tagsWithType('topics'); 

// retrieving models that have any of the given tags
NewsItem::withAnyTags(['first tag', 'second tag'])->get();

// retrieve models that have all of the given tags
NewsItem::withAllTags(['first tag', 'second tag'])->get();

// retrieve models that don't have any of the given tags
NewsItem::withoutTags(['first tag', 'second tag'])->get();

// translating a tag
$tag = Tag::findOrCreate('my tag');
$tag->setTranslation('name', 'fr', 'mon tag');
$tag->setTranslation('name', 'nl', 'mijn tag');
$tag->save();

// getting translations
$tag->translate('name'); //returns my name
$tag->translate('name', 'fr'); //returns mon tag (optional locale param)

// convenient translations through taggable models
$newsItem->tagsTranslated();// returns tags with slug_translated and name_translated properties
$newsItem->tagsTranslated('fr');// returns tags with slug_translated and name_translated properties set for specified locale

// using tag types
$tag = Tag::findOrCreate('tag 1', 'my type');

// tags have slugs
$tag = Tag::findOrCreate('yet another tag');
$tag->slug; //returns "yet-another-tag"

// tags are sortable
$tag = Tag::findOrCreate('my tag');
$tag->order_column; //returns 1
$tag2 = Tag::findOrCreate('another tag');
$tag2->order_column; //returns 2

// manipulating the order of tags
$tag->swapOrder($anotherTag);

Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Requirements

This package requires Laravel 8 or higher, PHP 8 or higher, and a database that supports json fields and MySQL compatible functions.

Installation

You can install the package via composer:

composer require spatie/laravel-tags

The package will automatically register itself.

You can publish the migration with:

php artisan vendor:publish --provider="Spatie\Tags\TagsServiceProvider" --tag="tags-migrations"

After the migration has been published you can create the tags and taggables tables by running the migrations:

php artisan migrate

You can optionally publish the config file with:

php artisan vendor:publish --provider="Spatie\Tags\TagsServiceProvider" --tag="tags-config"

This is the contents of the published config file:

return [

    /*
     * The given function generates a URL friendly "slug" from the tag name property before saving it.
     * Defaults to Str::slug (https://laravel.com/docs/5.8/helpers#method-str-slug)
     */
    'slugger' => null, 
];

Documentation

You'll find the documentation on https://docs.spatie.be/laravel-tags/v4.

Find yourself stuck using the package? Found a bug? Do you have general questions or suggestions for improving the laravel-tags package? Feel free to create an issue on GitHub, we'll try to address it as soon as possible.

If you've found a bug regarding security please mail [email protected] instead of using the issue tracker.

Testing

  1. Copy phpunit.xml.dist to phpunit.xml and fill in your database credentials.
  2. Run composer test.

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you've found a bug regarding security please mail [email protected] instead of using the issue tracker.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

License

The MIT License (MIT). Please see License File for more information.

laravel-tags's People

Contributors

adrianmrn avatar ahmad-moussawi avatar akoepcke avatar alexelev avatar alexvanderbist avatar andreybolonin avatar andypa avatar astrocorp avatar benjamincrozat avatar bsn4 avatar butochnikov avatar chrisbbreuer avatar delta1186 avatar dependabot[bot] avatar eggnaube avatar freekmurze avatar github-actions[bot] avatar israelortuno avatar king724 avatar lloricode avatar mokhosh avatar nielsvanpach avatar omranic avatar patinthehat avatar sebastiandedeyne avatar selimsalihovic avatar titonova avatar umairparacha00 avatar uyab avatar zupolgec avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-tags's Issues

QUESTION -> migration from rtconner/laravel-tagging

Is there an easy way to migrate my tags from the package rtconner/laravel-tagging to this package? The author of the other package has abandoned the package and composer suggests using the package from Spatie.

The only problem is the migration of the existing tags. Before I start writing a migration command I would like to know if someone has already written such a feature.

Problem when overriding the Tag Model

In short:

protected static function convertToTags
from HasTags.php

uses

if ($value instanceof Tag)

Well I use my own Tag Model and this test does not pass... so when I have Tag instances and pass them to the withAnyTag Scope for example, they are not recognized and therefore ...

Please change this place to:

if ($value instanceof $className)

Full code to replace for your convinience:

protected static function convertToTags($values, $type = null, $locale = null)
    {
        return collect($values)->map(function ($value) use ($type, $locale) {
            $className = static::getTagClassName();
            if ($value instanceof $className) {
                if (isset($type) && $value->type != $type) {
                    throw new InvalidArgumentException("Type was set to {$type} but tag is of type {$value->type}");
                }

                return $value;
            }


            return $className::findFromString($value, $type, $locale);
        });
    }

Error running migration on MariaDB 10.1.16

I'm running Laravel 5.3 on Valet on Mac OSX Sierra with MariaDB 10.1.16 and am encountering the following error when trying to run migration:

"SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'json not null, slug json not null, type varchar(255) null, order_column in' at line 1"

As far as I can tell from reading various posts and MariaDB docs, it seems (somehow) that MariaDB only supports JSON with "CONNECT" engine. My current work-around is to make the following changes:

from

$table->json('name');
$table->json('slug');

to

$table->text('name');
$table->text('slug');

Will this change have an adverse effect anywhere else in the package code?

TIA,
-martin.

PDOException on syncTags()

Here's the code from my controller:

...
$tags = explode(',',$request->input('tags'));
$userid = (int)\Auth::user()->id;
$url = \App\URL::where('id', '=', $id)->where('user_id', '=', $userid)->orderBy('updated_at', 'desc')->first();
$url->syncTags(['test1']);
$url->save();
return redirect('/l/'.\Hashids::encode($url->id));
...

my model implements the trait

class URL extends Model
{
use \Spatie\Tags\HasTags;
...

and I receive this error when attempting to execute syncTags() for the first time after running the migration

PDOException
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '>'$."en"' = ? and type is null limit 1' at line 1

Get tags attached to record

Is there a function where i can get all tags attached to a record ?

For example lets get first article $article = Article::find(1)->get();
How to get all tags attached to $article ?

Sorting Tag Documentation Confusion?

At this url https://docs.spatie.be/laravel-tags/v1/advanced-usage/sorting-tags

At these codes

//get all tags sorted on `order_column`
$orderedTags = Tags::ordered()->get(); 

//set a new order entirely
Tags::setNewOrder($arrayWithTagIds);

$myModel->moveOrderUp();
$myModel->moveOrderDown();

//move the tag to the first or last position
$myModel->moveToStart();
$myModel->moveToEnd();

$tag->swapOrder($anotherTag);

Do$myModelmeans Post Model (Just example for post it can be book or any) Instance or \Spatie\Tags\Tag Model instance??

I think $myModel should be $tagModel .

And in previous part of documentation we used $myModel for another thing like Post Model, isn't it ?

Or i am confused :(?

Error on creating tags manually

When I try to create a tag manually as written here, it will give me this error:

Type error: Return value of Spatie\Tags\Tag::getTranslations() must be of the type array, string returned

which is related to HasSlug.php class on line 12.

I also can't make an eloquent factory because of this error and must set attributes within array like this:

$factory->define(App\Tag::class, function (Faker\Generator $faker) {

    return [
        'name' => [$faker->word]
    ];
});

Views and front end examples

First of all, thank you so much for all the amazing packages. I am just learning Laravel and I am having a hard time getting the tags package to work. I followed all the installation steps but I am not really sure how I can add tags on the front end with a view. Are the sample code snippets supposed to be added in the model or should they be in the controller under their respective method (create, delete, etc)?
Also, I was looking at a turorial on Laravel News (https://laravel-news.com/how-to-add-tagging-to-your-laravel-app) and they are using javascript (Selectivize) in the views to attach the tags. Does that work the same with this package? Is there a repo with a sample project using that where I can see how everything is put together?
Sorry about all the confusion, I am still trying to learn my way around Laravel.

Example in Documentation does not work

Hi,

maybe I am just missing something, but as far as I see, the following example code from the docs is invalid:

$tag = Tag::create('gossip', 'newsTag');
$tag2 = Tag::create('headline', 'newsTag');

Since the Tag model does not overwrite the create method from the eloquent model you have to write something like this instead:

$tag = Tag::create([
            'name' => 'gossip', 
            'type' => 'newsTag'
]);
$tag2 = Tag::create([
            'name' => 'headline', 
            'type' => 'newsTag'
]);

Issue with translations.

Hi,

First of all thanks for the package. But now i got a issue/question.
I got the following inputs.

array:7 [▼
  "_token" => "a2r5e8ehAzyeu67kq2YPPM785hFgI1tokurBVMw3"
  "publish_date" => "2017-12-06"
  "is_published" => "Y"
  "title" => array:3 [▼
    "nl" => "dfqsdfsqdf"
    "fr'" => null
    "en" => null
  ]
  "categories" => array:3 [▼
    "nl" => "test, test"
    "fr" => "test,test"
    "en" => "test,test"
  ]
  "message" => array:3 [▼
    "nl" => "<p>dfsdfdsqfqdsf</p>"
    "fr" => null
    "en" => null
  ]
  "article_image" => UploadedFile {#456 ▶}
]

And the following controller:

public function store(NewsValidator $input): RedirectResponse
    {
        $input->merge(['author_id' => $input->user()->id]);

        if ($article = $this->newsRepository->create($input->except(['_token']))) {
            $article->addMedia($input->file('article_image'))->toMediaCollection('images');

            // Tags attachment.
            empty($input->categories['nl']) ?: array_map('trim', explode(',', $input->categories['nl']));

            flash("Het nieuws bericht is opgeslagen in het systeem.")->success();
        }

        return redirect()->route('news.admin.index');
    }

How can i integrate my tags with the needed translations. Into the my article logic? Because the docs look unclear to me.

Get all the tags from an Entity

I am new in Laravel as well as i am first time using your Service Provider I have a questions table in my MySQL database where every question belongs To many tags. I setup and config your provider properly. Here is my code.

in App\Question

class Question extends Model
{
    use HasTags;


}

in App\Http\Controller

class QuestionsController extends Controller
{
    ......
    public function store() {
        // create and save tags in tags table properly.
    }

}

in Terminal

>> $questions = App\Question::all();
=> Illuminate\Database\Eloquent\Collection {#833
     all: [
       App\Question {#805
         id: 1,
         title: "This is my development first question",
         slug: "this-is-my-development-first-question",
         details: "<p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's s
tandard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>",
         approved: 0,
         created_at: "2017-12-16 06:54:10",
         updated_at: "2017-12-16 06:54:10",
       },
       App\Question {#750
         id: 2,
         title: "This is my development first question",
         slug: "this-is-my-development-first-question",
         details: "<p>This package offers taggable behaviour for your models. After the package is installed the only thing you have to do is to add th
e <code>HasTags</code> trait to an Eloquent model to make it taggable.</p>",
         approved: 0,
         created_at: "2017-12-16 08:25:29",
         updated_at: "2017-12-16 08:25:29",
       },

// no associate tags return
>> $q[0]->tagsWithType('App\Question');
=> Illuminate\Database\Eloquent\Collection {#825
     all: [],
   }

How This will return all the tags that belongs to the given Entity Namespace. like https://cartalyst.com/manual/tags/2.0#get-all-the-tags-from-an-entity-namespace this Provider

Thank you

Has Tag

Is there an easy way to check if a model currently has a tag? Something like $model->hasTag('')?

Can't install package on Laravel 5.4

As mentioned in the Docs,

This package requires Laravel 5.3 or higher, PHP 7.0 or higher and a database that supports json fields such as MySQL 5.7 or higher.

My php version is 7.1.2 operating laravel 5.4 with Mysql database 5.7. When i head to install the package via composer command : composer require spatie/larave-tags it resulted in a dependency error.
screenshot from 2017-09-14 12-49-49

As shown in the error log, it requires illuminate/database ~5.5.0 which is i think operates with Laravel 5.5.

SQLSTATE[HY000]: General error: 2036 (SQL: select * from `tags` where `name`->'$."nl"' = testtag and `type` is null limit 1)

I am using version 1.4
On my dev machine it works like a charm, but today I deployed it to my acceptation server and
now I am getting the error message mentioned in the title of this issue, while using Tag::findOrCreate.

When I copy and past the sql statement in the query runner of SequelPro I still get an error message
But when I put quotes around the 'testtag' word, the query run's perfectly

I am using Mysql version 5.7.19 on my dev machine an 5.7.18-6 on my acceptation server
I am using php7.0.10 on my dev machine and php7.0.20 on my dev acceptation server

Another difference I can see is that on my dev machine mysqlnd is loaded, but not on the acceptation server.

Please advice.

Kind regards

using your own tag model

Hi there,

Boy I feel kinda stupid for asking this.. specially since there's already two other issues opened regarding extending the tag model and using your own.

So I have my own Tag model to which I want to add all the functionality of your tag model. So that model extends Spatie\Tags\Tag

All good so far

Then, you say "All you need to do is override the getTagClassName method from the HasTags trait."

Sounds simple enough. My question is, since I don't want to edit a vendor file. Does that mean I should create my own trait, so I can extend it with Spatie\Tags\HasTags, and in that trait I should override the

    public static function getTagClassName(): string
    {
        return Tag::class;
    }

method and have it return my custom tag model that extends Spatie\Tags\Tag ?

That's what I would do.. but was wondering if there was another way of overriding the getTagClassName method of the HasTags trait without creating a trait of my own.

Guess I just haven't done a lot of overriding like this in the past.

Thanks!

Issue importing/exporting sql dump file with tags table

Perhaps this isn't a bug, but I'm having problems with the format of the tags table. I exported the entire site database in a sql dump. Then I tried to import that file into a staging database. The import goes well until it hits the tags table. Then this error is thrown.

Cannot create a JSON value from a string with CHARACTER SET 'binary'.

I haven't worked with JSON in MySQL before this package. So, I'm sure I'm missing something. Does anyone have experience with this?

withAnyTags and withAllTags doesn't ignore $type parameter when null

withAnyTags and withAllTags returns empty collection when you don't specify $type param, in case Tag has type set. Possibly same problem as in #28

Is this the intended behavior? It doesn't seem to be because I didn't notice any tests for it.

The problem is in

    public static function findFromString(string $name, string $type = null, string $locale = null)
    {
        $locale = $locale ?? app()->getLocale();
        return static::query()
            ->where("name->{$locale}", $name)
            ->where('type', $type)
            ->first();
    }

shouldnt it be?

    public static function findFromString(string $name, string $type = null, string $locale = null)
    {
        $locale = $locale ?? app()->getLocale();
        return static::query()
            ->withType($type)
            ->where("name->{$locale}", $name)
            ->first();
    }

because scopeWithType ignores $type when null

SQLSTATE[42000]: Syntax error or access violation: 1064

Hi all, I am trying to do an example of tagging. I have appended my model with the HasTags trait and when I do

        $id = Questions::create([
            'body' => request('title'),
            'skillset_id' => request('skillsetId'),
            'tags' => ['red', 'blue']
        ])->id;

I get:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '>'$."en"' = ? and `type` is null limit 1' at line 1 (SQL: select * from `tags` where `name`->'$."en"' = red and `type` is null limit 1)

I am on

  • Windows 10
  • MariaDB 10.3.2
  • MySQL 5.7.19

I have successfully installed and added the migration tables, but the creating of tags is where I fail.

Creating tag with type throws exception

Hi,

Awesome package, but I am having trouble using the types. There is one thing that don't seem to work:

$tag = Tag::create($characteristic, 'beerCharacteristicTag');

returns the following error:

[Symfony\Component\Debug\Exception\FatalThrowableError]

Type error: Argument 1 passed to Illuminate\Database\Eloquent\Model::create() must be of the type array, string given, called in /home/vagrant/Code/beer/app/Console/Commands/ScrapeBeers.php on line 121

where as $tag = Tag::findOrCreate($characteristic, 'beerCharacteristicTag'); works just like it should.

PS. There is a small typo in the documentation. Double colon instead of semi.

$tagWithType = Tag::create('headline', 'newsTag'):

detachTags on delete

Hello,

I'm suprised deleting the model does not cascade deleting its taggable relationship (like media-library does, for example)

Is it a forgotten feature or is there a real reason (I didn't get yet) for not dropping those orphan relationships ?

Best,

Laurent

Error when publishing package migrations

Getting this error:
Can't locate path: </home/vagrant/my-project/vendor/spatie/laravel-tags/src/../database/migrations/_create_tag_tables.php.stub>

I suspect the path is incorrect in the service provider?

Tags also searchable via slug.

First of all, thanks for the great work.

While searching for tags i noticed you can only search for the name, not the slug.
Since the slug is normalized it would be easier to search for the slug.

For example i have a tag with the name: Hello.
Model::withAnyTags(['hello'])->get();
Model is not found because the tag contains a uppercase H.

So Hello & hello are not the same.
It would be easier to search for a normalized tag, so uppercase doesn't matter.

getTranslations() issue when editing tag

I'm trying to update a tag, but I'm missing something.

$tag = Tag::findOrFail($id);
$tag->name = $request->name;
$tag->type = $request->type;
$tag->save();

But that throws this

Type error: Return value of Spatie\Tags\Tag::getTranslations() must be of the type array, string returned

Using your own tag model

I might be doing something wrong here, but the documentation references using your own tag model. I've overridden the get TagClassName method:

use Illuminate\Database\Eloquent\Model;

class YourModel extends Model
{
   public static function getTagClassName(): string
   {
       return YourTagModel::class;
   }
}

However, in the tags method the code still refers to the Tag::class:

public function tags(): MorphToMany
{
        return $this
            ->morphToMany(Tag::class, 'taggable')
            ->orderBy('order_column');
}

Is this intentional and I need to override this method as well or should it use my custom Tag Model?

Thanks

Can't add tags

MySQL: 5.7.20
Laravel: 5.5.21
PHP: 7.1.3

Every time I try to add tags I receive this error

Call to undefined method Illuminate\Database\Query\Builder::syncWithoutDetaching()

I've tried using attachTags(), syncTags() and attachTag(), and all give the same error.

$post->attachTags(['one', 'two']);
$post->syncTags(['one', 'two']);
$post->attachTag('tag 1');

I'm attempting to attach tags right after creating a $post

Locale with retrieving WithAnyTags

Is it possible to add locale as an optional parameter to pass when calling WithAnyTags or WithAllTags, for that matter, so it can pass it to convertToTags ? Or is there some other way and I'm doing something wrong.

Cheers.

Sync a single Tag

I would appreciate some help with the following problem:
I need to toggle (attach/detach) a tag to a model but to leave any other tags alone.

Consider the following:
There are 4 tags in the DB Tag1, Tag2, Tag3, Tag4
$model has Tag1, Tag2 and Tag3 attached.

I want to call something like a 'toggleTag' function and see the following behaviour:

  • $model->toggleTag('Tag1') // $model now has Tag2 & Tag3.
  • $model->toggleTag(['Tag3', 'Tag4']) // $model now has Tag2, & Tag4
  • $model->toggleTag(['Tag1', 'Tag5']) // $model now has Tag1, Tag2, Tag4 & Tag5 (Tag5 is created, and with type if passed).

I am also doing all this using tag types so I need to allow for that as well.

I must be missing something but I'm struggling to see whether or not a given tag exits on a model (which will allow me to attach, detach or create and attach).

Thanks,

Database syntax error when adding tags

I'm not sure if this is a bug but on a fresh setup and migration when I try and add an array of tags like:

//I'm using Laravel 5.4.30 with mariadb.

$tags = ['foo', 'bar', 'baz'];
$story-> attachTags($tags); //also tried syncTags

I keep getting the following mysql error:

  [Illuminate\Database\QueryException]
  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your
   MariaDB server version for the right syntax to use near '>'$."en"' = ? and `type` is null limit 1' at line 1 (SQL: select * from `tags
  ` where `name`->'$."en"' = foo and `type` is null limit 1)

  [PDOException]
  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your
   MariaDB server version for the right syntax to use near '>'$."en"' = ? and `type` is null limit 1' at line 1

I'm not sure what could be causing this but it looks like it might have something to do with the translation feature? Although I'm not using that and just wanted english tags. It looks like it has something to do with an empty $ variable?

I also get the same issue when trying to add a single tag.

Thanks for your help, the package seems really useful!

Question - How to extend the tags model?

Hi,

Ive set up this package and its been very easy to install and use, so thank you for building it and sharing it 👍

I have gone through the docs on extending the model for this package, but I am not sure how it would actually be implemented. Can you provide more details in the example (here or in the docs) ?

My objective is to extend the tags so the user can add a "color" for each tag (color makes it easy to identify tags, similar to gmail). So If I have a tag for "finance" the color could be could be #0000ff and tag for "medical" could have a color value of #00ff00 etc.
Would this be possible using this package?

I have created a migration to extend the DB fields to add a color field, but where to I keep my custom tag model and how do I reference it in my other models.

I would appreciate it if you can point me in the right direction!

Unable to sync tags when using types feature

Unless I'm mistaken, there doesn't appear to be any way to sync tags when using 'types' to categorise tags.

Is there a strategy for syncing tags when using the types feature, or any plans to implement this functionality?

attachTag creates an extra row in the database

Seems like attachTag is acting strangely. It seems to create an additional line, which includes the data for the whole model, not just the tag.

foreach ($characteristics as $characteristic) {
    $tag = Tag::findOrCreate($characteristic);
    $beer->attachTag($tag);
}

image

Using $beer->syncTags($characteristics); is the workaround but I would like to attach typed tags and you cannot use syncTags for that one.

Helper method to retrieve tag usage summary

Thanks for sharing such a great library! I needed a way retrieve a summary of tag usage as an associative array (name => total), but I didn't see an easy way to do this in the library. I added the function below as a helper to my model, but I'm sure there's a more elegant way to do it :).

    public static function getAllTags()
    {
        $tags = DB::table('taggables')
            ->selectRaw('name, count(tag_id) as total')
            ->join('tags', 'tags.id', '=', 'taggables.tag_id')
            ->groupBy('tag_id')
            ->orderBy('name', 'asc')
            ->get();

        // create an associate array as [name => total]
        $tagArray = [];

        foreach($tags as $tag) {
            $name = json_decode($tag->name);
            $tagArray[$name->en] = $tag->total;
        };

        ksort($tagArray); // sort the tags alphabetically by the name key

        return $tagArray;
    }

Syncing tags

So I have quite a few tags that I created like this.

$tag = Tag::findOrCreate($request->name, $request->type);

For example:

$request->name = 'web development';
$request->type = 'primary';

The tag gets created. That seems to work fine. Woohoo.
Then, on another page, I tried to attach a model to the tag. I would do this:

$company->syncTags($all_tags);

If "web development" was one of the tags in the $all_tags array, it doesn't get recognized. Instead, another new tag gets created with the exact same name and slug except it has an empty type.

Why does it ignore the tag that already exists?

Model::withAnyTags or Model::withAllTags returning zero models.

Might be user error, so bear with me.

Create a new model, Resource in my case:
image

Then attach a tag (which auto-creates the tag):
Correction: Screenshot shows Resource->attachTags which is incorrect. I just didn't take a new screenshot using correct attachTag('test').
image

Verify tag was created:
image

Attempt to retrieve model just created and tagged:
image

My expected result would be a collection with my one Resource in it. Again, it might be user error too.

Thanks!

Error on creating tag

Hi,

I'm trying to create a tag with this code: Tag::create(['name' => 'my tag']).

But when I tun the code I get this error: Type error: Return value of Spatie\Tags\Tag::getTranslations() must be of the type array, string returned. I'm using tinker to quickly create a tag.

Selecting items tagged with tagsWithType

$tag = Tag::findOrCreate('gossip', 'newsTag');
$tag2 = Tag::findOrCreate('headline', 'newsTag');
NewsItem::withAnyTags([$tag, $tag2])->get();

the above code return NewsItem empty

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.