Best way to implement article view count in Laravel?

554 Views Asked by At

I have a dilemma. I need to implement most read article in my API laravel app based on view count of the article. In my article table I have view_count column. Is it ok that I do this on my show method

public function show($id)
{
  $article = Article::where('id', $id)->first();
  $article->increment('view_count');
  return $article;
}

Or will this slow down response or will it not work if I have many hits on this route at the same time? Or is it better to use some third party counter like google analytics? I would appreciate any suggestion, thanks.

1

There are 1 best solutions below

0
behzad m salehi On

absolutely if your platform stress (many requests per snapshot of time) and/or load (many requests on average) is high, incrementing DB row is not the best solution u can do.

  • you can keep articles views in some in-memory caches like Memcache or Redis and persist them in the database after specific hours or days.

  • you can use another database, especially in this case time-series databases (TSDB) like influx DB for keeping track of your views and logs and etc ...

  • you can use google tag manager and/or other cloud SAAS services to change the history log.

  • you can create a separate table to save the most popular articles and change their engine for optimizing them for heavy writing.

  • you can add database nodes and use clustering and so many other options.

just consider what is properly based on your scale and your requirements