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 on Laravel Daily

AI Agents/IDEs for Laravel: May 2026 (Claude Code, Codex, OpenCode, etc)

7 lessons
52 min

Testing in Laravel 13 For Beginners

26 lessons
1 h 41 min read

Queues in Laravel 13

18 lessons
1 h 12 min read