ホーム > Laravel > How to Display 'Hashtags' in a List in Laravel
Laravel

How to Display 'Hashtags' in a List in Laravel

Thank you for your continued support.
This article contains advertisements that help fund our operations.

This article explains how to display 'hashtags' in a list in Laravel.

Laravel 8
Vue 2

When the article was originally published, it was created with the above environment, but it now works perfectly fine with Laravel 11 and Vue 3 as well.

Prerequisites

  1. posts table
  2. post_tag table
  3. tags table

This is focused on displaying the data, assuming the above tables exist.

For saving data with a many-to-many relationship, please refer to the following article.

How to Save and Display a Many-to-Many Relationship in Laravel【belongsToMany】

Define the Relationship in Laravel

Write the relationship in the Post model.

Models/Post.php

    public function tags()
    {
        return $this->belongsToMany(Tag::class);
    }

Fetch the List with Tags in the Controller

    public function index()
    {
        $posts = Post::with('tags')->get();
        //dd($posts);
        return view('post/index', compact('posts'));
    }

With this code, the data will be fetched along with the tags relationship.

Display the List in Blade

This section explains how to display the data in a Laravel .blade.php file.

You can display the tags as follows.

Note that since tags is a collection, you'll need to loop through it with a foreach.

@foreach($posts as $post)
  {{ $post->title }}
  @foreach($post->tags as $tag)
    {{ $tag->name }}
  @endforeach
@endforeach

Display the List in Vue

The relationship and controller remain the same, and since only columns are added, you can retrieve the data as shown below.

<template>
  <div v-for="post in posts">
    <p v-for="tag in post.tags" :key="`tag${post.id}-${tag.id}`">
      {{tag.name}}
    </p>
  </div>
</template>

That's it.

I hope this is helpful to someone.

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!