What makes it special is that you can define the logic to divide it into multiple types such as "popular content for the past few days, weeks, months and even year". Aside from that, you can also retrieve the popular post by total views or unique views which will be very powerful depending on the use case.
Prerequisite
In order for you to continue this tutorial you have to read my other post on "How to implement visitor views/visitor counter in Laravel application". In that post, I have discussed how to anonymously count your visitor visit on your page and display the stats to the public.
Once you have read and implemented it, let's move on to getting the most popular content on your website.
Implementation
There are several implementations for this and it's described below.
Get the total views for the past few days
/* total views for the last 1 day */ Post::orderByViews('desc', Period::pastDays(1)) ->take(10) ->get(); /* total views for the last 3 days */ Post::orderByViews('desc', Period::pastDays(3)) ->take(10) ->get(); /* total views for the last 7 days */ Post::orderByViews('desc', Period::pastDays(7)) ->take(10) ->get();
Post::orderByUniqueViews('asc', Period::pastDays(3)) ->get(); /* descending */ Post::orderByUniqueViews('desc', Period::pastDays(3)) ->get(); /* ascending */
Get the total views since specified time
If you prefer to get the total views since the specified time, you can define using the code like below.
Period::subSeconds(int $seconds); Period::subMinutes(int $minutes); Period::subHours(int $hours); Period::subDays(int $days); Period::subWeeks(int $weeks); Period::subMonths(int $months); Period::subYears(int $years);
$postSince2MonthAgo = Period::subMonths(2); /* post since 2 months ago */ Post::orderByViews('desc', $postSince2MonthAgo) ->take(10) ->get();
Get the total views for between 2 dates
On the other hand, to get the views for between 2 periods you will have to define the "starting" and "ending" of the date. You can use the normal date written in string `2020-06-06` otherwise user carbon instance `Carbon::createFromDate(2020, 05, 05)`
$startDateTime = Carbon::createFromDate(2020, 05, 05); /* carbon instance */ $endDateTime = '2020-06-06'; $mayToJune = Period::create($startDateTime, $endDateTime); views($post) ->period($mayToJune) ->count();
$from2020to2021 = Period::create('2020', '2021'); views($post) ->period($from2020to2021) ->count();