How to Display the Number of Likes 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 for Laravel articles
Summary of how to display the number of likes in a list with Laravel
Laravel Framework 8.83.8
Vue 2.6
Premise
Assuming there is a posts
table and a likes
table, this content is specific to display.
Please refer to the following article for the "Like" feature.
How to Implement a "Like" Feature in Laravel
Writing a Relation in Laravel
From the Post model's perspective, since Like is one-to-many, write the relation with hasMany
.
Models/Post.php
public function likes()
{
return $this->hasMany('App\Models\Like');
}
Setting the Number of Likes in the Controller to Retrieve the List
How to Count the Total of a Related Number and Display it in a List in Laravel【withCount】
(Routing configuration and blade file generation are omitted in the article)
public function index()
{
$posts = Post::withCount('likes')->get();
//dd($posts);
return view('post/index',compact('posts'));
}
With this description, the data is retrieved with the column "likes_count" added.
Displaying a List with blade×Laravel
Since the column has been added, it can be retrieved just like other columns.
@foreach($posts as $post)
<div>{{ $post->likes_count }}</div>
@endforeach
Displaying a List with Vue × Laravel
The relation and controller are the same, only the column has been added, so it can be easily retrieved as follows.
<template>
<div v-for="post in posts">{{post.likes_count}}</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 it!
Popular articles
Deploying a PHP 7.4 + Laravel 6 Project to AWS EC2
Implementing Breadcrumbs in Laravel with laravel-breadcrumbs