How to Display 'Hashtags' in a List in Laravel
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
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
- posts table
- post_tag table
- 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.