1. Go to this page and download the library: Download hamedrajabpour/laravel-tags library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
hamedrajabpour / laravel-tags example snippets
// 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();
// using tag types
$tag = Tag::findOrCreate('tag 1', 'my type');
// 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);