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
// Group the view counts by project ID.
Redis::hincrby('project-views', $project->id, 1);
})
// Console/Kernel.php
$schedule->command(UpdateProjectViews::class)->daily();
// Console/Commands/UpdateProjectViews.php
// Retrieve all project view counts from Redis.
$views = Redis::hgetall('project-views');
/*
[
(id) => (views)
1 => 213,
2 => 100,
3 => 341
]
*/
// Iterate over each project's view count.
foreach ($views as $projectId => $projectViews) {
// Update the project view totals in MySQL.
Project::find($projectId)->increment('views', $projectViews);
}
// Clear the processed view counts from Redis.
Redis::del('project-views');