Skip to main content
Quick Tip

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

Enjoyed This Tip?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.