Skip to content

Quick start

From an empty install to a trending list in five steps. Each one links to the page that covers it in full.

Terminal window
composer require cyrildewit/eloquent-viewable:^9
php artisan vendor:publish --provider="CyrildeWit\EloquentViewable\EloquentViewableServiceProvider" --tag="migrations"
php artisan migrate

See Installation for publishing the config and for models keyed by a UUID or ULID.

use Illuminate\Database\Eloquent\Model;
use CyrildeWit\EloquentViewable\Concerns\InteractsWithViews;
use CyrildeWit\EloquentViewable\Contracts\Viewable;
class Post extends Model implements Viewable
{
use InteractsWithViews;
}

Add the views middleware to the route that shows the model. It records a view for every successful GET, and the cooldown keeps a reader who refreshes the page from counting twice:

use CyrildeWit\EloquentViewable\Http\Middleware\RecordViews;
Route::get('/posts/{post}', ShowPost::class)
->middleware(RecordViews::using('post', cooldown: 30));

Or call views($post)->record() in the controller. Crawlers, prefetches and HEAD requests are dropped either way. See Recording views and Cooldowns.

use CyrildeWit\EloquentViewable\Support\Granularity;
use CyrildeWit\EloquentViewable\Support\Period;
views($post)->count(); // every view
views($post)->unique()->period(Period::pastDays(7))->count(); // unique visitors this week
$trend = views($post)->period(Period::pastDays(7))->compare();
$trend->percent; // 17.2, against the week before
$series = views($post)
->period(Period::pastDays(30))
->remember(60)
->countByInterval(Granularity::Day);
$series->labels(); // ['2026-09-01', '2026-09-02', ...]
$series->values(); // [14, 22, ...]

See Retrieving counts and Caching.

Post::orderByViews()->paginate(); // most viewed first
foreach (views(Post::class)->trending(10) as $entry) {
$entry->viewable; // the post
$entry->count; // its views lately
}

See Ordering and filtering and Trending.