Installation
Require the package to your Laravel application using composer.
composer require cyrildewit/eloquent-viewable
php artisan vendor:publish --provider="CyrildeWit\EloquentViewable\EloquentViewableServiceProvider" --tag="migrations" php artisan migrate
php artisan vendor:publish --provider="CyrildeWit\EloquentViewable\EloquentViewableServiceProvider" --tag="config"
Implementation
To allow the package to record the total user visit, your model class will have to implement the "Viewable Interface". Aside from that, make use of the "InteractsWithViews" trait to provide the functionality of recording and retrieving the views count.
use Illuminate\Database\Eloquent\Model; use CyrildeWit\EloquentViewable\InteractsWithViews; use CyrildeWit\EloquentViewable\Contracts\Viewable; class Article extends Model implements Viewable { use InteractsWithViews; // others code ommited }
Recording Views
In order for you to record the views, you can call the "views" helper method and pass in the model that you have defined to be viewable and chain with the "record" method to increment the count value by one.
views($article)->record();
This code is typically written inside the controller method and it will look something like below. Do note that you can record multiple views by defining the code multiple times.
// ArticleController.php public function show(Article $article) { views($article)->record(); return view('articles.show', compact('article')); }
views($article) ->cooldown($minutes = 3) ->record();
Retrieving Views
Finally, to retrieve the total number of views for the model, just call the helper method and chain it with the "count" method as follows. This will retrieve the total article count and it's accessible with the variable you have defined.
$totalViews = views($article)->count();
use CyrildeWit\EloquentViewable\Support\Period; // Example: get views count from 2020 upto 2021 views($article) ->period(Period::create('2020', '2021')) ->count();
I hope this tutorial is helpful for you and if there's any question, do comment out below and let's start the discussion. Also, don't forget to share it with your friend as well and I would appreciate it a lot. Cheers and have a good try.