Use Redis to track page views

Tracking something like page views with MySQL can be quite a performance hit when dealing with high traffic. Redis is much better at this. You can use Redis and a scheduled command to keep MySQL in sync on a fixed interval.

1Route::get('{project:slug', function (Project $project) {
2 // Instead of $project->increment('views') we use Redis
3 // We group the views by the project id
4 Redis::hincrby('project-views', $project->id, 1);
5})
1// Console/Kernel.php
2$schedule->command(UpdateProjectViews::class)->daily();
3 
4// Console/Commands/UpdateProjectViews.php
5// Get all views from our Redis instance
6$views = Redis::hgetall('project-views');
7 
8/*
9[
10 (id) => (views)
11 1 => 213,
12 2 => 100,
13 3 => 341
14]
15 */
16 
17// Loop through all project views
18foreach ($views as $projectId => $projectViews) {
19 // Increment the project views on our MySQL table
20 Project::find($projectId)->increment('views', $projectViews);
21}
22 
23// Delete all the views from our Redis instance
24Redis::del('project-views');

Tip given by @Philo01

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord