Git Product home page Git Product logo

laravel-tagging's Introduction

Laravel Taggable Trait

Latest Stable Version Total Downloads License Build Status Scrutinizer Code Quality

This package is not meant to handle javascript or html in any way. This package handles database storage and read/writes only.

There are no real limits on what characters can be used in a tag. It uses a slug transform to determine if two tags are identical ("sugar-free" and "Sugar Free" would be treated as the same tag). Tag display names are run through Str::title()

composer require rtconner/laravel-tagging

Install and then Run the migrations

The package should auto-discover when you composer update. Then publish the tagging.php and run the database migrations with these commands.

php artisan vendor:publish --provider="Conner\Tagging\Providers\TaggingServiceProvider"
php artisan migrate

Setup your models

class Article extends \Illuminate\Database\Eloquent\Model
{
	use \Conner\Tagging\Taggable;
}

Quick Sample Usage

$article = Article::with('tagged')->first(); // eager load

foreach($article->tags as $tag) {
	echo $tag->name . ' with url slug of ' . $tag->slug;
}

$article->tag('Gardening'); // attach the tag

$article->untag('Cooking'); // remove Cooking tag
$article->untag(); // remove all tags

$article->retag(array('Fruit', 'Fish')); // delete current tags and save new tags

$article->tagNames(); // get array of related tag names

Article::withAnyTag(['Gardening','Cooking'])->get(); // fetch articles with any tag listed

Article::withAllTags(['Gardening', 'Cooking'])->get(); // only fetch articles with all the tags

Article::withoutTags(['Gardening', 'Cooking'])->get(); // only fetch articles without all tags listed

Conner\Tagging\Model\Tag::where('count', '>', 2)->get(); // return all tags used more than twice

Article::existingTags(); // return collection of all existing tags on any articles

Documentation: More Usage Examples

Documentation: Tag Groups

Documentation: Tagging Events

Documentation: Tag Suggesting

Configure

See config/tagging.php for configuration options.

Lumen Installation

Documentation: Lumen

Credits

Further Reading

laravel-tagging's People

Contributors

0plus1 avatar cliffbrown avatar computeus avatar davericher avatar drolean avatar elbakly avatar epic-kaso avatar firtzberg avatar imanghafoori1 avatar jakejohns avatar james2doyle avatar jbardnz avatar juresyahya avatar kirananils avatar kousukekun avatar lpmi-13 avatar marcusmoore avatar mcmains avatar nicolasbinet avatar oschettler avatar remcom avatar rtconner avatar stueynet avatar uibar avatar vinicius73 avatar vkbansal avatar vtluan36 avatar woutrrr avatar xoshbin avatar yamenarahman 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-tagging's Issues

incorrect encoding for non-latin symbols

found a bug,

this commit shows the difference between symbols, take a look:
6b7d830

compare two versions of $char_map array:

after moving from src/Conner/Tagging/Tag.php to src/Conner/Tagging/TaggingUtil.php
the encoding seems to have broken up

was able to fix the bug by copy-pasting the old array

Get all tags that belong to a user

I noticed none of the tag tables have an associated user_id key or anything. What's the best way to fetch all tags that were created by a specific user?

String to Integer Conversion issue on PgSQL

I'm not sure if anyone else has run into this issue but I have been getting a lot of errors when trying to use withAnyTag and withAllTag scopes in pg databases.

After some research it seems that it was a conversion issue since it was trying to do a join from an Integer id column from my models to the taggable_id field in the tagging_tagged table.

I was able to hack around this by channing the taggable_id field to an integer.

Not sure if there's something we could do to make sure things are cast to the proper type from the query scopes in this package or maybe ship two different migration for string vs integer primary keys?


Note: Looking around this error may not be replaceable on MySQL databases since MySQL will do automatic field casts while PG and others require explicit type cast declarations.

Tags versionning

What if this library could allow this:

$model->setTagsVersion('machine');

// TaggedTrait.php
public function setTagsVersion($verison)
{
    $this->tagsVersion = $version;
}

// filter rows based on "version" tagged column 
public function tagged()
{
    $relation = $this->morphMany('Conner\Tagging\Tagged', 'taggable');
    // not sure if $morphMany accepts where chaining method
    return ($this->version) ? $relation->where('version', $this->tagsVersion) : $relation;
}

Problem with related models

Scenario: I have ForumTopic which has the tagging trait. I then do something like Auth::user()->topicsSubscribed(). This is a many to many relationship to ForumTopic.

public function scopeWithAnyTag($query, $tagNames) {
    $tagNames = self::makeTagArray($tagNames);

    $tagNames = array_map('Conner\Tagging\Tag::slug', $tagNames);

    return static::whereHas('tagged', function($q) use($tagNames) {
        $q->whereIn('tag_slug', $tagNames);
    });
}

This is returning all topics when I do $subscribed->withAnyTag(...), instead of the tags for the related model.

For example, if I change the following, it works. But, obviously this isn't the solution :)

public function scopeWithAnyTag($query, $tagNames) {
    $tagNames = self::makeTagArray($tagNames);

    $tagNames = array_map('Conner\Tagging\Tag::slug', $tagNames);

    return Auth::user()->topicsSubscribed()->whereHas('tagged', function($q) use($tagNames) {
        $q->whereIn('tag_slug', $tagNames);
    });
}

Installation Details Complete?

Ive tried your installation instructions but i get the error:

Trait 'MyProject\Repositories\Conner\Tagging\Taggable' not found, if i put the 'use' package statement where you suggest.
If i put it outside my class declaration then the error goes away but i get:

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

Can you give some more complete installation instructions. The composer and artisan steps worked fine but this is frustrating.

Missing tables in database

Illuminate\Database\QueryException with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'artotheek5.tagging_tagged' doesn't exist (SQL: select count(*) as aggregate from tagging_tagged where tagging_tagged.taggable_id = 1 and tagging_tagged.taggable_type = App\News and tag_slug = test limit 1)'

I have followed all steps and it seems that I am missing some tables in the database, they don't seem to be added by artisan migrate. Can someone help me to see what I'm doing wrong, thanks.

Delete unused tags not working

The function shouldDeleteUnused in TaggableTrait.php should reference the config value of delete_unused_tags not untag_on_delete

Difficulties when trying to install and use the package

Hi Rob (or anybody else listening),

first: Thanks for the package!

When I follow the steps in the readme the trait does not seem to work out of the box.

Issues:

  • After following the readme steps I had to copy the migrations to my migrations folder by hand so the tables are created when calling php artisan migrate (maybe intended to do so but not (yet) in the readme)
  • When adding the trait with use Conner\Tagging\TaggableTrait; I get a PHP Fatal error: Trait 'App\Conner\Tagging\TaggableTrait' not found. I worked around it by changing it to use \Conner\Tagging\TaggableTrait;
  • after the change I get another error when trying to call e.g. $mymodel->addTag('mytag'); in one of my database seeders stating:
    [BadMethodCallException] Call to undefined method Illuminate\Database\Query\Builder::addTag()

Now I am stuck. Maybe I do something wrong because I am not very experienced with laravel nor with php. So please excuse any bothering with noob questions ... :-)

Any help would be great. Also I really would like to use your package to save me some time.

Environment: fresh laravel 5 project on homestead. My models live in the App namespace as by default laravel 5 installation.

Regards,
Thomas

Question about tag retrieveing

I haven't tried but in have scenerio.

Let's assume there are three article.

1. post1 | tag1,tag2,tag3
2. post2 | tag1,tag2,tag4
3. post3 | tag1,tag5,tag6

If I want to retrieve all posts that have "tag1 AND tag2", response will be post1 and post2.
Another request for all posts that have "tag1 AND tag2 AND tag3", response will be only post1.

Can laravel-tagging handle this with withAllTags() method?

Here's a sql fiddle demo what I want.

Also thanks for your efforts.

suggest column

I found that there is a column called "suggest" column on database table. What is its purpose?

all symbols tag has no slug

This is a great plugin! It's so easy to set up and use. Thank you.

When entering a tag name like &&&&""'' (I know, crazy) there is no slug. Perhaps in this case the slug could be a uniqid() or something, so there is still a slug, even if it's not related to the tag content.

Clearly, there won't be many times a tag ends up empty after removing all special chars - but who knows what people will use this for.

Thanks!

Unable to publish config/migrations.

The original path __DIR__.'/../../../config/tagging.php' => config_path('tagging.php'), seems to be wrong. I had to change this in my basic setup to _DIR__.'/../config/tagging.php' => config_path('tagging.php'),.

Possible to create unattached tags?

Is this possible? In my app, video clips will have tags attached, but the user should be able to simply create the tags themselves, and then add them to clips at their leisure.

toArray() on collection not working

I'm trying to get this package to work but I can't seem to retrieve the tags in a readable form.

I do $show->tagged()->toArray() and it throws and error that the method is not available.
The collection does exist and I can even call first() on it. So why doesn't toArray() work?!

Am I missing something here?

Laravel 5

How can I use this package in L5?

No issue

Great work!

Installed and functioning in no time.

adding new tag

can we do some thing like this.

  1. add tag .
    2.attach tag to articles ?

Doc explain how to attach tag , but how can i add tag first . :)

Wrong Migrations. config/tagging.php 'primary_keys_type' => 'integer' doesn't work.

I'm installing rtconner/laravel-tagging by composer. And "laravel-tagging/migrations/2014_01_07_073615_create_tagged_table.php" looks different than on github.
GitHub version:
Schema::create('tagging_tagged', function(Blueprint $table) {
$table->increments('id');
if(\Config::get('tagging.primary_keys_type') == 'integer') {
$table->integer('taggable_id')->unsigned()->index();
} else {
$table->string('taggable_id', 36)->index();
}
$table->string('taggable_type', 255)->index();
$table->string('tag_name', 255);
$table->string('tag_slug', 255)->index();
});

Composer version:
Schema::create('tagging_tagged', function(Blueprint $table) {
$table->increments('id');
$table->string('taggable_id', 36)->index();
$table->string('taggable_type', 255)->index();
//$table->morphs('taggable');
$table->string('tag_name', 255);
$table->string('tag_slug', 255)->index();
});

What should I do? Or what shoud you do? ) I would be very thankful if you helped me.

existingTags() not works

    public static function existingTags() {
        return Tagged::distinct()
            ->join('tagging_tags', 'tag_slug', '=', 'tagging_tags.slug')
            ->where('taggable_type', '=', get_called_class())
            ->orderBy('tag_slug', 'ASC')
            ->get(array('tag_slug as slug', 'tag_name as name', 'tagging_tags.count as count'));
    }

I'm sure
get_called_class() get value '\App\Models\Article'
so can not found any record in database
'taggable_type'='Article'

*->tagged returns empty collection

I just upgraded to L5 and I have noticed that the tags stopped working. The database is populated, the model uses the trait, but the tags are not retrieved.

I can provide any information necessary, but I haven no clue how to debug this at the moment. Everything should work.

The class using it extends Model instead of Eloquent as it used to be in L4

Publishing does not work completely

When I try to publish it only copies the config.php.

XXX@XXX:~/XXX$ php artisan vendor:publish --provider="Conner\Tagging\TaggingServiceProvider"
Copied File [/vendor/rtconner/laravel-tagging/config/tagging.php] To [/config/tagging.php]
Publishing Complete!

I had to copy the migration files per hand.

How to override TaggingUtil class?

I tried to add some customised functions to the TaggingUtil class. How to extend it so that the TaggableTrait class can call the customised TaggingUtil class. What I would like to do is no need to change the anything of your library in vendor folder but allow me to customise the functions. Because I added other columns to the database table.

Config not read

Hi,

it seems that the Laravel 4 version of this package doesn't consider the configs in config.php. We are trying to avoid the ucfirst of the tag name but it doesn't work. Any ideas?

Invalid version string "^1.2.2"

Running composer require rtconner/laravel-tagging "~1.0.2" gives an error:

[RuntimeException]
Could not load package classpreloader/classpreloader in http://packagist.org: [UnexpectedValueException] Could not parse version constraint ^1.2.2:  
Invalid version string "^1.2.2"    


[UnexpectedValueException]                                                  
Could not parse version constraint ^1.2.2: Invalid version string "^1.2.2"  

I had been using laravel-tagging with Laravel 4, but upgrading my project to laravel 5 is now impossible since laravel-tagging keeps getting an error. What should I try?

insert error

I can not add tag Because this error was displayed

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'taggable_id' cannot be null (SQL: insert into tagging_tagged (tag_name, tag_slug, taggable_type, taggable_id) values (Navid, navid, Post, ))

Sorry for my bad English

Taxonomy Feature

Hi, I'm using this package in my CMS project. Your package is a great solution for tagging and thanks for sharing! I wanna ask you that; are you planning to development a Taxonomy feature as part of your tagging package?

Error SQL insert taggable_id

Hi,
I'm having problem using the package (tried master & version 4), when I call tag function I get this error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'taggable_id' cannot be null (SQL: insert into tagging_tagged (tag_name, tag_slug, taggable_type, taggable_id) values (Gardening All Day Long, gardening-all-day-long, Article, ))

it seems taggable_id is not entered and it's define in the db not to be NULL.
I'm using laravel 4.2 latest.

Edit:
Well I found the problem - I needed to save the Article to the DB before calling tag function (which is reasonable because we need the ID to save as a reference)

Eager loading for tagNames

Hello,

If I am trying to use eager for tagNames. Something like:
$allMedia = Media::with("tagged")->get();
foreach($allMedia as $item) {
print_r($item->tagNames());
}
but it doesn't work with current implementation in tagNames:
$tagged = $this->tagged()->get(array('tag_name'));

It would if you remove "get" column and just use $this->tagged:
foreach($this->tagged as $tagged) {
$tagNames[] = $tagged->tag_name;
}

Problem with Article::allTags();

When i use Article::allTags(); in my ArticlesController, I got QueryException (42S22):

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'count' in 'field list' (SQL: select distinct `tag_slug`, `tag_name`, `count` from `tagging_tagged` where `taggable_type` = Article order by `tag_slug` asc)

I lookat my table "tagging_tagged", I don't see any field with name "count". Why I have this problem?

Eager loading?

Hello,

Great work on this package, I can not get eager loading to work? What's the trick ? L5.

ta

WithAllTags is slow.

I'm using withAllTags() on a database with 10000 rows in a table and 53655 rows in tagging_tagged, paginating the results then passing it to the view for me to loop through. It takes around 10 seconds just to return the videos with the specified tags, is there a way to speed this up?

'untag_on_delete' does not delete "everything"

Hi there,

I have 'untag_on_delete' => true, in my config/tagging.php

But when I do Model::destroy($id); my model is destroyed correct. In the table tagging_tagged it is deleted correctly, but the in the table tagging_tags there is still a entry with the used tag. Only the count is set to zero.

Is this how it should work? Or should the row in the tagging_tabs table also be deleted? And when it is kept: why?

Thanks for your answer.

Method title does not exist.

When adding a tag the application throws an error Method title does not exist.

I've tried to trace it and it get thrown at \Str::title on line 137 from TaggableTrait.php it only happens on my server and not when I run the application locally.

Looks like the application can't invoke the methods from the class that is loaded on line 3 or something in that way.

Cyrillic cymbols bug

Please, fix this:
...
public function tag($tagName) {
$tagName = trim($tagName);
if(!strlen($tagName)) { return; }

    $tagSlug = Str::slug($tagName); // return "" for cyrillic words =(

...

withAnyTag returns SQLSTATE[42S22]

The tagging and untagging functions work fine. However both withAnyTag and withAllTags generate a database error.

I am calling this from the controller:

Item::withAnyTag('Something')->get();

Which returns:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'has' in 'where clause'
(SQL: select * from items where has = ?) (Bindings: array ( 0 => 'tagged', ))

The tagging_tagged table is populated:

id taggable_id taggable_type tag_name tag_slug
1 20 Item Something something

I'd appreciate any suggestions you have for getting this to work. Thanks.

allTags() missing

Are you sure that the allTags() method/scope is in the trait? I can't seem to find it in the trait and it throws an exception when trying to use it.

oxxf7to

problem with php artisan migrate:reset

I get the following error:

{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"Class 'CreateTagsTable' not found","file":"C:\inetpub\wwwroot\elearning-api\src\vendor\laravel\framework\src\Illuminate\Database\Migrations\Migrator.php","line":297}}

Eager loading tags

Is this possible? Because if I have a list of 1000 tagable entities, with each 10 tags, you can imagine that the amount of queuries become huge when getting them out of a forloop

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.