Language:

Search

Cómo implementar Tagging a Modelos Laravel con Tagify

  • Share this:
Cómo implementar Tagging a Modelos Laravel con Tagify

Introduction

Adding tags to your Laravel app can improve overall search-ability, so If your Laravel app requires to add or associate tags to any of the models, Laravel Tagify will make your life easier.

Installation

To install the package, simply install it from composer.

composer require usamamuneerchaudhary/laravel-tagify

Once the package is installed, run the migrations which will create two tables, tags and taggables.

Also Read: One to Many Polymorphic Relationship in Laravel

php artisan migrate

and finally, don't forget to add the TagifyServiceProvider to app.php

Usamamuneerchaudhary\LaravelTagify\TagifyServiceProvider::class,

Usage

For instance, you're running a blog on Laravel, and your posts need some tags with it. In your Post model, add the Taggable trait likeso,

Also Read: Laravel Livewire comments

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Usamamuneerchaudhary\LaravelTagify\Taggable;
class Post extends Model
{
    use Taggable;
}

Also Read: Standardise API Responses in Laravel

Once thats set, lets' play around with it a bit.

Add a Tag

$tags =['Laravel','PHP'];
$post->tag($tags);

Untag a Tag

$post->untag(['Laravel]);

Untag all Tags

$post->untag();

Retag a tag to Post Model

$post->retag(['Eloquent','mysql']);

Get all Tags

$post->tags;

Scopes to get associated tags

App\Model\Post::withAllTags(['laravel','php']); //will return if has all tags
App\Model\Post::withAnyTags(['laravel','php','python']); //will only return the ones associated, and ignore the 
ones which are not.
App\Model\Post::hasTags(['laravel','php']); //check if a model has tags


Github Repository: Laravel Tagify Package

TWT Staff

TWT Staff

Writes about Programming, tech news, discuss programming topics for web developers (and Web designers), and talks about SEO tools and techniques