How to Display "Hashtags" in a List with Laravel
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
⇨ Click here for the table of contents of Laravel articles
This article summarizes how to display "hashtags" in a list with Laravel
Laravel Framework 8.83.8
Vue 2.6
Prerequisites
Assumes the existence of the following tables:
- posts table
- post_tag table
- tags table
This content is specialized for display assuming these tables exist.
For functionality to save in a many-to-many relationship, please refer to the following article.
How to Save and Display Many-to-Many Relations in Laravel with belongsToMany
Writing Relations in Laravel
Check the relation in the Post model.
(For those who have already saved, new descriptions should not be necessary)
Models/Post.php
public function tags()
{
return $this->belongsToMany('App\Tag');
}
Setting Tags in the Controller to Retrieve a List
public function index()
{
$posts = Post::with('tags')->get();
//dd($posts);
return view('post/index',compact('posts'));
}
With this description, data is retrieved with the tags relation added.
Displaying a List in blade × Laravel
You can display tags as follows.
Note that since there are multiple tags, you will need to loop through them using foreach.
@foreach($posts as $post)
{{ $post->title }}
@foreach($post->tags as $tag)
{{ $tag->name }}
@endforeach
@endforeach
Displaying a List with Vue × Laravel
The relations and controller remain the same, as only columns have been added, so you can easily retrieve them as follows.
<template>
<div v-for="post in posts">
<p v-for="tag in post.tags">{{tag.name}}</p>
</div>
</template>
Conclusion
That's all.
I hope it will be helpful to someone.
For feedback or complaints, please contact me via Twitter DM.
That's all!
Popular Articles
Deploying a PHP7.4 + Laravel6 Project to AWS EC2
Implementing Breadcrumbs in Laravel with laravel-breadcrumbs