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.

Route::get('{project:slug', function (Project $project) {
// Instead of $project->increment('views') we use Redis
// We group the views by the project id
Redis::hincrby('project-views', $project->id, 1);
})
// Console/Kernel.php
$schedule->command(UpdateProjectViews::class)->daily();
 
// Console/Commands/UpdateProjectViews.php
// Get all views from our Redis instance
$views = Redis::hgetall('project-views');
 
/*
[
(id) => (views)
1 => 213,
2 => 100,
3 => 341
]
*/
 
// Loop through all project views
foreach ($views as $projectId => $projectViews) {
// Increment the project views on our MySQL table
Project::find($projectId)->increment('views', $projectViews);
}
 
// Delete all the views from our Redis instance
Redis::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:
  • 68 courses (1188 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses