<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zekaryas G on Medium]]></title>
        <description><![CDATA[Stories by Zekaryas G on Medium]]></description>
        <link>https://medium.com/@zekijohn?source=rss-ea14bd64faba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZiVjVV8fLsoSkkZijPJvLg.jpeg</url>
            <title>Stories by Zekaryas G on Medium</title>
            <link>https://medium.com/@zekijohn?source=rss-ea14bd64faba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 00:44:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zekijohn/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Tagging Models In Laravel]]></title>
            <link>https://zekijohn.medium.com/tagging-models-in-laravel-9e70163b3c99?source=rss-ea14bd64faba------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e70163b3c99</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[tagging]]></category>
            <category><![CDATA[laravel-framework]]></category>
            <category><![CDATA[tag]]></category>
            <dc:creator><![CDATA[Zekaryas G]]></dc:creator>
            <pubDate>Fri, 15 Oct 2021 08:40:30 GMT</pubDate>
            <atom:updated>2022-11-21T08:36:47.437Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mVVqsuGn76Q08en3" /><figcaption>Photo by <a href="https://unsplash.com/@angelekamp?utm_source=medium&amp;utm_medium=referral">Angèle Kamp</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>if you are building a blog or news website no question you need tagging system. in this post that is exactly what we are going to do.</p><p>we will use <strong>spatie/laravel-tags</strong> package to tag a model in Laravel application which is easy to use and has awesome features you cannot find in other tagging packages for example support for translating tags, multiple tag types and sorting capabilities.</p><h4>ok… lets jump write into the example.</h4><p>I’ll assume you’re already working on a Laravel Project( or <strong>already installed Laravel</strong>) and you want to tag models.</p><h3>Step #1 Install <strong>spatie/laravel-tags</strong></h3><p>from your project directory run:-</p><pre>composer require spatie/laravel-tags</pre><p>once installation finishes publish migration files and migrate.</p><pre>php artisan vendor:publish -- provider=&quot;Spatie\Tags\TagsServiceProvider&quot; --tag=&quot;tags-migrations&quot;</pre><pre>php artisan migrate</pre><p><a href="https://beyondbuilder.io/"><strong>Tailwind CSS Visual Builder.</strong></a><strong> </strong>Build and mange beautiful, Unique, Design forward and lightning fast websites with ease.<a href="https://beyondbuilder.io/"><strong> </strong><br>Join the wait list now to get a free coupon/discount when we launch.</a></p><h3>Step #2 Setup Model</h3><p>if you have not created your model yet create it first. I’ll create Post model</p><pre>php artisan make:model Post -mcr </pre><p>I used -mrc option let me explain it</p><p>-m means create a migration for the model. -c means create controller and -r means create the controller with resource (index, store, show, destroy, edit methods). you can use them separately if you want.</p><p>open the model you want to make taggable and add the HasTags trait (don’t forget to import <strong>Spatie\Tags\HasTags</strong>). in my case I want to make my App\Models\Post Model taggable.</p><pre>&lt;?php</pre><pre>namespace App\Models;</pre><pre>use Illuminate\Database\Eloquent\Factories\HasFactory;<br>use Illuminate\Database\Eloquent\Model;<br><strong>use Spatie\Tags\HasTags;</strong></pre><pre>class Post extends Model<br>{<br>    use HasFactory, <strong>HasTags</strong>;<br>}</pre><p>now your model will have methods like <strong>attachTag, attachTags, detachTags, syncTags, syncTagsWithType, withAnyTags, withAllTags</strong> and many more.</p><p>let see how to use them.</p><h3>Step #3 Using Tags</h3><p>now whenever you want to attach tags to a model use</p><pre>$post-&gt;<strong>attachTags</strong>([&#39;tag 1&#39;, &#39;tag 2&#39;]);<br>//or<br>$post-&gt;<strong>attachTag</strong>(&#39;single tag&#39;);</pre><p>here is how I used it in my PostController@store method</p><pre>&lt;?php</pre><pre>namespace App\Http\Controllers;</pre><pre>use App\Models\Post;<br>use Illuminate\Http\Request;</pre><pre>class <strong>PostsController </strong>extends Controller<br>{<br>    /**<br>     * Store a newly created resource in storage.<br>     *<br>     * <a href="http://twitter.com/param">@param</a>  \Illuminate\Http\Request  $request<br>     * <a href="http://twitter.com/return">@return</a> \Illuminate\Http\Response<br>     */<br>    public function <strong>store</strong>(Request $request)<br>    {<br>        // validation(if any)</pre><pre>        // create your model<br>        $post = Post::create([<br>            &#39;title&#39; =&gt; &#39;10 Love Quotes&#39;, <br>            &#39;body&#39; =&gt; &#39;post body&#39;<br>        ]);</pre><pre>        // <em>Attaching Tags:-</em><br>        $post-&gt;<strong>attachTags</strong>([&#39;quote&#39;, &#39;love&#39;, &#39;tag 3&#39;, &#39;tag 4&#39;]);</pre><pre>        // rest of your logic. <br>        // may be flash message and redirect or return json response</pre><pre>    }<br>}</pre><p>let’s see a couple of other useful methods you can use:-</p><pre><strong>//create a tag </strong><br>$tag = Tag::create([&#39;name&#39; =&gt; &#39;my tag&#39;]);  </pre><pre><strong>//update a tag </strong><br>$tag-&gt;name = &#39;another tag&#39;; <br>$tag-&gt;save();</pre><pre><strong>//use &quot;findFromString&quot; instead of &quot;find&quot; to retrieve a certain tag </strong>$tag = Tag::findFromString(&#39;tag 1&#39;)  </pre><pre><strong>//create a tag if it doesn&#39;t exist yet </strong><br>$tag = Tag::findOrCreateFromString(&#39;tag 100&#39;);</pre><pre><strong>// detaching tags</strong><br>$newsItem-&gt;detachTags(&#39;tag 1&#39;);<br>$newsItem-&gt;detachTags([&#39;tag 1&#39;, &#39;tag 2&#39;]);</pre><pre><strong>// delete tag</strong><br>$tag-&gt;delete();</pre><pre><strong>// syncing tags</strong><br>$newsItem-&gt;syncTags([&#39;first tag&#39;, &#39;second tag&#39;]);</pre><p>when you detach tags the detached tags will not be deleted from database if you want to do so use</p><pre><strong>// find tag first</strong><br>$tag = Tag::findFromString(&#39;another tag&#39;);</pre><pre><strong>// call delete method just like any other models</strong><br>$tag-&gt;delete();</pre><h3>Retrieving Models</h3><p>to retrieve a model (in this example posts) with given tags you can use:-</p><pre>// retrieving models that have any of the given tags<br>Post::<strong>withAnyTags</strong>([&#39;tag 1&#39;, &#39;tag 2&#39;])-&gt;get();<br><br>// retrieve models that have all of the given tags<br>Post::<strong>withAllTags</strong>([&#39;quote&#39;, &#39;love&#39;, &#39;tag 3&#39;])-&gt;get();</pre><h3><strong>Using Types (advanced usage)</strong></h3><blockquote>In your application you might want to have multiple collections of tags. For example: you might want one group of tags for your News model and another group of tags for your Post model.</blockquote><pre><strong>//creating a tag with a certain type $tagWithType = </strong>Tag::findOrCreate(‘headline’, ‘newsTag’);</pre><h3>Conclusion</h3><p>In this post we have seen how you can tag your models in laravel application using <strong>spatie/laravel-tags </strong>but there are more features in this package you should check out for example support for <strong>translating tags</strong>, <strong>multiple tag types</strong> and <strong>sorting capabilities. </strong>I will cover these topics on the upcoming post.</p><p>Check out <a href="https://spatie.be/docs/laravel-tags/v4">Spatie Documentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e70163b3c99" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>