Bloganueva Logo Bloganueva

Bloganueva Has Tags

2019-07-25 16:15:50

I finally added tags to my website! I’ve tried 2 separate times before, but I never could get it to work. I encountered everything that was stopping me before on this most recent attempt, but this time I was able to get past them. Something just clicked this time.

I’ve previously been able to use php artisan tinker to add tags to posts, but I couldn’t translate this action and related ones into my PostsController and blade file. No matter what I tried at the time, it didn’t work. This time, I got back to the tinker part. I approached it one step at a time.

I followed different tutorials to help me every time I tried. I used different approaches because none of them were working. I was really confused because, if I followed the instructions for the most part, it should work, right? WRONG (lol). The tutorials I was using had different code than each other and myself; so it made it more difficult. What was tripping me up was for some reason in the previous 2 attempts was my code wasn’t retrieving my post’s ID from my database. I determined that this was the problem in my second attempt, but none of my code worked. This time, I was able to figure out a way to do it!

$post->save();
$post = $post->latest()->first();
$post->tag()->sync((array)$request->input('tag'));

In the tutorials I was using, you would just see some version of the first line and the last line. In my situation I needed the middle line for everything to work. I needed to explicitly retrieve the latest post from the database AFTER it was saved. Once a post gets saved to my database, that’s when it’s given an ID. With this second line, I’m pulling the post after it’s saved, therefore also pulling in it’s newly given ID. Then the last line attaches the tag(s) to the post!

With this code, I FINALLY ADDED A TAG TO A POST. Before I got really excited, I started testing out other things to try and break it. Once I figured out this step and nothing else broke, EVERYTHING started falling in to place.

It sucks knowing how close I was the last 2 times, but I’m just glad I fiiinally figured it out! For posts to have tags on a website, you need to have a polymorphic relationship. That means posts can have more than one tag, and tags can belong to more than one post. This makes it a little bit more difficult to do than say, categories (which I also have). Categories can belong to multiple posts, but posts canNOT have multiple categories. Most blogs and websites have this tagging ability, so I sort of felt left out, even though I was putting that feeling on myself. Well, not anymore! I’m heeere with everyone else, and it feels great to have conquered this problem after nearly 2 years! I literally love coding so much!

Updated at: 2019-07-29 23:14:04

Tags: development software technology laravel php


Read More From development