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 viewsforeach ($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 instanceRedis::del('project-views');
Tip given by @Philo01