Search

Programming
Programming

We provide developers and engineers the guides and tutorials they...

Content
Content

Content is king. It's not just about how you're going to write, b...

Events
Events

Looking for an engaging connection with thousands of other people...

How to implement Tagging to Laravel Models with Tagify

How to implement Tagging to Laravel Models with Tagify

Add tags to your Laravel models easily with Tagify. Our step-by-step tutorial shows you how to implement tagging functionality in your Laravel app efficiently.

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

About author

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

View all posts (402)
Your experience on this site will be improved by allowing cookies Cookie Policy