Laravel taggable Add tag function to your model

Source: Internet
Author: User
Tags ming

Function description

Use the easiest way to provide a powerful "tag" feature for your data model.

: Gift: Project Address: https://github.com/summerblue/laravel-taggable

This project was modified in the Rtconner/laravel-tagging project, adding a bit of functionality:

    • The label name is unique;
    • Increased Etrepat/baum dependency, allowing tags to support unlimited levels of tag nesting;
    • Chinese slug Pinyin Auto-generated support, thanks to Super elder brother Overtrue/pinyin;
    • Provide complete test cases to ensure code quality.

Note: This project only supports 5.1 LTS

: Heart: This project is maintained by the @Summer of the EST group team.

Unlimited level tag nesting

The integrated Etrepat/baum allows the label to have a dependency.

$root = tag::create ([' Name ' = ' root ');//Create sub-label $child1 = $root->children ()->create ([' name ' = ' Child1 ']); Child = Tag::create ([' name ' = ' Child2 ']); $child->makechildof ($root);//Bulk build tree $tagtree = [    ' name ' = = ' Roottag ',    ' children ' = = ['        name ' = ' = ' l1child1 ',            ' children ' and ' = ' [                ' name ' = ' l2child1 '],                [' name ' = ' l2child1 '],                [' name ' = = ' l2child1 ']            ,        [' name ' = ' l1child2 '],        [' name ' = ' l1child3 '],    ]; Tag::buildtree ($tagTree);

For more related operations please see: Etrepat/baum.

Label name Rule description

    • Special symbols and spaces in the tag name will be replaced;
    • Smart tag slug generated, will generate the name corresponding to the Chinese pinyin slug, such as: label, Biao-qian, pinyin is the same time will be added random values;

Label name cleanup using: $normalize _string = Estgroupe\taggable\util::tagname ($name).

Tag::create ([' tag name ']);//Name: Tag name//Slug:biao-qian-mingtag::create ([' Table signature ']);//Name: Table Signature//slug:biao-qian-ming-3243 (Back 3243 for random, resolve phonetic conflict) tag::create ([' tag name ']);//Name: Tag-name//slug:biao-qian-mingtag::create ([' Tag! name ']);//Name: Label-name//slug : biao-qian-ming

Installation Instructions:

Installation

Composer require estgroupe/laravel-taggable "5.1.*"

Install and perform migration

In the providers array of config/app.php, add:

' providers ' = = Array (    \estgroupe\taggable\providers\taggingserviceprovider::class,);
PHP artisan vendor:publish--provider= "Estgroupe\taggable\providers\taggingserviceprovider" PHP artisan Migrate

Please read the config/tagging.php file carefully.

Create tag.php

Not necessary, but it is recommended that you create your own project-specific tag.php file.

     

Modify the config/tagging.php file:

    ' Tag_model ' = ' \app\models\tag ',

Join Taggable Trait

      

"Label Status" indicator

Taggable can track whether a model has been tagged:

' No ' $article->is_tagged//' yes ' $article->tag (' Tag1 '); $article->is_tagged;//' no ' $article->untag (); $article->is_tagged//This is fast$taggedarticles = Article::where (' is_tagged ', ' yes ')->get ()

First you need to modify the config/tagging.php file:

' Is_tagged_label_enable ' = true,

Then add the following in your model's database creation script:

 
    Increments (' id ');            ...            Add this line            $table->enum (' is_tagged ', array (' Yes ', ' no '))->default (' no ');            ...            $table->timestamps ();}        );}    }

"Recommended Label" indicator

It is convenient for you to implement the "recommended tag" function, just mark the Suggest field as true:

$tag = estgroupe\taggable\model\tag::where (' slug ', ' = ', ' blog ')->first (); $tag->suggest = true; $tag->save ();

That is, it can be read in the following ways:

$suggestedTags = estgroupe\taggable\model\tag::suggested ()->get ();

Rewrite the Util class?

Most common operations occur in the Util class, you want to get more customization power, please create your own Util class, and register the service provider:

Namespace My\project\providers;use Estgroupe\taggable\providers\taggingserviceprovider as ServiceProvider;use Estgroupe\taggable\contracts\taggingutility;class Taggingserviceprovider extends ServiceProvider {    /**     * Register the service provider.     *     * @return void     *    /Public Function register ()    {        $this->app->singleton (taggingutility:: class, function () {            return new Mynewutilclass;        });}    }

And then in

Note Mynewutilclass must implement the Estgroupe\taggable\contracts\taggingutility interface.

Usage examples

$article = Article::with (' tags ')->first (); Eager load//gets all the label foreach ($article->tags as $tag) {echo $tag->name. ' With URL slug of '. $tag->slug;} Hit label $article->tag (' Gardening '); Attach the Tag$article->tag (' Gardening, floral '); Attach the Tag$article->tag ([' Gardening ', ' floral ']); Attach the Tag$article->tag (' gardening ', ' floral '); Attach the tag//in bulk through tag IDs tag $article->tagwithtagids ([[+]);//Remove the label $article->untag (' Cooking '); Remove Cooking tag$article->untag (); Remove all tags//re-hit label $article->retag ([' Fruit ', ' Fish '); Delete current tags and save new Tags$article->retag (' Fruit ', ' fish '); $article->retag (' Fruit, Fish '); $tagged = $ article->tagged; Return Collection of rows tagged to Article$tags = $article->tags; return Collection The actual tags (is slower than using tagged)//Gets the binding tag name array $article->tagnames (); Get array of related tag names//gets the article object that hit the "any" tag article::withanytag (' GardeniNg, Cooking ')->get (); Fetch Articles with any tag listedarticle::withanytag ([' Gardening ', ' Cooking '])->get (); Different syntax, same result as Abovearticle::withanytag (' Gardening ', ' Cooking ')->get (); Different syntax, same result as above//get hit the "All Inclusive" label article Object Article::withalltags (' Gardening, Cooking ')->get (); Only fetch articles with all the tagsarticle::withalltags ([' Gardening ', ' Cooking '])->get (); Article::withalltags (' gardening ', ' Cooking ')->get (); Estgroupe\taggable\model\tag::where (' Count ', ' > ', 2)->get (); Return all tags used more than twicearticle::existingtags (); Return collection of all existing tags on any articles

If you do, you can use the following tag reading features:

Get label Tag::bytagslug (' biao-qian-ming ') via Slug->first ();//Get label tag::bytagname (' tag name ') by name->first ();// Get an array of tags by name array tag::bytagnames ([' Tag name ', ' label 2 ', ' label 3 ') ')->first ();//Get the label array Tag::bytagids ([three]) via tag IDs array First ();//Get an array of IDs by name array $ids = Tag::idsbynames ([' Label name ', ' label 2 ', ' label 3 '])->all ();//[N/A]

Label Event

Taggabletrait provides the following two events:

estgroupe\taggable\events\tagadded; estgroupe\taggable\events\tagremoved;

Monitoring Tag events:

\event::listen (Estgroupe\taggable\events\tagadded::class, function ($article) {    \log::d ebug ($article- Title. ' was tagged ');});

Unit Test

For the basic use case test, see: tests/commonusagetest.php.

To run the test:

Composer Installvendor/bin/phpunit--verbose

Thanks

    • Special Thanks To:robert Conner-http://smartersoftware.net
    • Overtrue/pinyin
    • Etrepat/baum
    • Made with love by the EST group-http://estgroupe.com/
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.