How to add Tagging to your Laravel App

Published on by

How to add Tagging to your Laravel App image

In recent years, tagging systems have become a popular way of categorizing items, and you can find them in almost every app. From blog posts to todo lists, they all have tagging implementations.

Let’s look at how easy integrating a tagging system is in a Laravel app. In the Laravel Links app I created a few weeks back I decided to add tagging to the links and what follows is instructions for setting it up.

Installing a Tagging package

The community has created several tagging packages, and you will need to research which one suits your use case. Here are three of the most popular ones I found:

I choose the Laravel Tagging package by rtconner, and the installation is simple.

First require the package:

composer require rtconner/laravel-tagging "~2.0"

Open config/app.php and add it to the providers array:

Conner\Tagging\Providers\TaggingServiceProvider::class,

Now run publish the vendor folder with Artisan:

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

Finally, migrate the database:

php artisan migrate

Now we are ready to add the trait to our model. My model is named “Links.php” and here is the class:

use Conner\Tagging\Taggable;
 
class Links extends Model
{
use Taggable;
 
protected $table = 'links';

That is all it takes to get set up and ready to use; however, it leaves out an important step. Tagging typically needs JavaScript and styling to make it easy for the user to select an existing tag or add a new one.

Installing jQuery and Selectize

Selectize by Brian Reavis is a jQuery based plugin that turns an input field into a tagging system. This plugin can easily be installed through NPM and then set up using Browserify with Elixir.

In your terminal install jQuery and Selectize and automatically save them to your package.json with the following:

npm install jquery --save
npm install selectize --save

If you open package.json now you should see the following dependencies:

"dependencies": {
"laravel-elixir": "^3.0.0",
"bootstrap-sass": "^3.0.0",
"jquery": "^2.1.4",
"selectize": "^0.12.1"
}

Bootstrap and Elixir come pre-included in a default Laravel install. Which will now use to finish off the installation.

Create a file resources/assets/js/app.js and include the following:

window.$ = window.jQuery = require('jquery')
require('selectize');
var bootstrap = require('bootstrap-sass');
 
$( document ).ready(function() {
$('#tags').selectize({
delimiter: ',',
persist: false,
valueField: 'tag',
labelField: 'tag',
searchField: 'tag',
options: tags,
create: function(input) {
return {
tag: input
}
}
});
});

What this is going to do is utilize browserify to pull in jQuery, Selectize, and Bootstrap JavaScript into our file. We assign jQuery to the window so that plugins can read it from the global scope. Then we are assigning the Selectize Plugin to any input with the id of “tags”.

Before we can compile, we need to adjust our gulp file.

elixir(function(mix) {
mix.sass('app.scss')
.browserify('app.js');
});

The unique change here is the call to browserify. That call allows our “require” lines to pull in the proper dependencies.

Bootstrap Styles

Since Bootstrap is already included we can utilize it to handle our styles. Open app.scss and uncomment this line:

@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";

This will pull in bootstrap directly from the node_modules directory.

All that is left is to pull in styles for Selectize. The plugin ships with bootstrap support and it’s just a matter of importing that css file:

@import "node_modules/selectize/dist/css/selectize.bootstrap3";

Now if you run gulp everything should compile, and your views will display properly.

Displaying and Saving Tags

In our template, we need to create two new items. An input field for adding tags and a JavaScript array of existing tags so Selectize can autocomplete.

In our controller pull out all existing tags and assign them to the view:

$tags = Links::existingTags()->pluck('name');
return view('create', compact('tags'));

Then in our create template add the tags input:

<input type="text" name="tags" id="tags">

Next a new JavaScript array of tags:

<script>
var tags = [
@foreach ($tags as $tag)
{tag: "{{$tag}}" },
@endforeach
];
</script>

Now when the form is submitted create the model and attach the tags:

// Create the link first
$link = Links::create([...]);
 
// Now add tags
$link->tag(explode(',', $request->tags));

With this all set you should now be able to save tags and autocomplete existing tags.

More tagging options

The Laravel Tagging package includes a lot more features than what has been shown so far. Here is a list of all available features:

Eager Loading

$link = Link::with('tagged')->first(); // eager load

Removing Tags

$link->untag('laravel'); // remove Laravel tag
$article->untag(); // remove all tags

Syncing Tags

$link->retag(['tutorial', 'package']); // delete current tags and save new tags

Fetching by Tag

Link::withAnyTag(['laravel','tutorial'])->get(); // fetch with any tag listed
 
Link::withAllTags(['package', 'php'])->get(); // only fetch with all the tags
Eric L. Barnes photo

Eric is the creator of Laravel News and has been covering Laravel since 2012.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3 image

Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3

Read article