'Get total number of post views of all posts from a user in laravel 9
I am trying to get the total number of views of all posts from each user and display it to the user dashboard.
I added a "reads" column to my article migration.
public function up()
{
Schema::table('articles', function (Blueprint $table) {
$table->bigInteger('reads')->default(0)->index();
});
}
I have a method in my Article (post) Model called incrementReadCount() which counts the views of each article.
public function incrementReadCount()
{
$this->reads++;
return $this->save();
}
In my ArticlesController I display the number of views on an article
public function show(Article $article, User $user)
{
$articles = $user->articles()->get();
if(Cookie::get($article->id)!=''){
Cookie::set('$article->id', '1', 60);
$article_reads = $article->incrementReadCount();
}
return view('article.article', compact('article','user', 'articles', 'article_reads'));
}
How do I display the total number of all article views on the user dashboard? My home controller:
public function index(User $user, Article $article)
{
return view('dashboard', compact('user', 'article'));
}
Solution 1:[1]
In your index method, grab all user's articles and do a summation over "reads" column:
$user->articles()->sum('reads');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sahand Moghadam |
