cyrildewit / eloquent-viewable Goto Github PK
View Code? Open in Web Editor NEWAssociate views with Eloquent models in Laravel
License: MIT License
Associate views with Eloquent models in Laravel
License: MIT License
Hey, can you give me a advice, how make Eager Loading on my model with it?
Is it possible that you can add a method like Article::getTotalViews(), that adds the views of all the articles together.
for example, i have a site that has a section with news-items, blog-posts, scheduled-events, it would be nice to see wich section of my site attracts the most pageviews.
I know i can het the total myself by looping through all the articles, but it would be nice to have a built-in method for it.
I dont know What visitable_id is
Integrity constraint violation: 1048 Column 'visitable_id' cannot be null (SQL: insert into page-views
(visitable_id
, visitable_type
, ip_address
, updated_at
, created_at
) values (, App\Doctor, 139.190.64.77, 2018-01-11 09:01:32, 2018-01-11 09:01:32))
see here in the query above, it is taking visitable_id as empty value
please tell me what the issue is
The first version (1.0
) of this package provided a method called addPageViewThatExpiresAt
. It accepted an expiry date as first argument. This method checked if the model was stored in the session with an expiry date. If not, the view would be stored in the database.
This feature was removed when I created the second version (2.0
), but since it was useful to some users I decided to bring an improved version of it back.
I've got some ideas in my mind, but I'm interested in some feedback!
// 1. (old way)
// @param DateTime $expiryDateTime
$post->addViewThatExpiresAt(Carbon::now()->addHours(3)); // 3 hours after now
// 2.
// @param int $minutes
$post->addViewWithDelay(3 * 60); // 3 hours after now
// 3. (same as 2 but with two different behaviours)
// @param DateTime|int $delay
// 3.1
$post->addViewWithDelay(2 * 60); // 2 hours after now
// 3.2
$post->addViewWithDelay(Carbon::parse('2018-06-10 12:00:00')); // expires at 2018-06-10 12:00:00
Delay is probably not the right word for this behaviour.
Fixes #69
Make it available to easily configure custom cache lifetimes for various views counts.
Currently, every views count will be cached for a fixed number of minutes that's defined in the eloquent-viewable
config file.
Simplified version:
'cache' => [
'cache_views_count' => [
'lifetime_in_minutes' => 60, // this line
],
],
It would be great to be able to define custom cache lifetimes for various views counts. This is very useful when you want to cache for example the 'total number of views' for one day instead of one hour.
method
in your viewable modelDefine the different cache lifetimes in a viewable model class within a public method, so the ViewableService
can read it and use it when needed.
Example: Post model
public function registerViewsCountsCacheLifetimes($registrar)
{
$registrar->add(Period::pastDays(5), false, 30) // past5days, normal, 30 minutes
$registrar->add(Period::upto(Carbon::now()), true, 5 * 60) // 2018-04-12 14:58:55 , unique, 5 days
}
Works exactly like the above one, but then you configure it inside your config file.
'views_counts_cache_lifetimes' => [
Post::class => [
[
'period' => Period::pastDays(5),
'lifetime' => 30,
],
[
'period' => Period::upto(Carbon::now()),
'unique' => true,
'lifetime' => 5 * 60,
],
],
],
->getViews()
and ->getUniqueViews()
methodEasily change the lifetime in minutes through an optional parameter in ->getViews()
and ->getUniqueViews()
.
$post->getViews(null, 5 * 60); // 5 days
$post->getViews(Period::pastDays(5), 3 * 60); // 3 days
$post->getUniqueViews(Period::since(Carbon::create(2014)), 20 * 60); // 20 days
I don't think this is a clean solution, because ->getViews(null, 5 * 60)
requires null as first argument to retrieve the total number of views. But could be a possibility.
Great package, easy to integrate. I'm wondering if you have any plans to allow ordering model items by visit count?
being able to order by total visits as well as 24h, 7d and 14d would be great.
Caching visits counts is harder than I thought. I created this issue to discuss my ideas with the package users.
Caching visits counts is getting done by storing the count under a unique key based upon the model, since date, upto date and type (not unique = normal, unique = unique).
The current problem right now is, that we don't know if the since and upto dates are reactive. By that I mean if they are like: past xx days, past xx weeks, next xx days etc. This is because the transformation is done before the package retrieves the date.
For example: now()->subDays(4)
is always different, because it's based upon the current time. If we could somehow now about these transformations, we can cache them differently.
To make this solution more elegant, I have chosen to use method chaining. This way, our models aren't getting filled with all kinds of methods.
// 1 Since and Upto date options
// 1.1 Static dates
->since(<Carbon instance>)
->upto(<Carbon instance>)
// 1.2 Reactive dates
-><since|upto><Sub|Add><Seconds|Minutes|Days|Weeks|Months|Years>() // 2 * 2 * 6 = 24 methods
e.g. ->sinceSubDays(3),
->sinceSubYears(2),
->uptoSubWeeks(10)
// 2 Only unique visits?
->unique()
// 3 Get the visits count
->count(); // or get() ?
Examples:
// Example 1 (static dates)
$post->getVisitsCount()
->since(Carbon::parse('01-03-2007'))
->upto(Carbon::parse('01-03-2013'))
->count();
// Example 1 (reactive date)
$post->getVisitsCount()
->sinceSubDays(4)
->count();
$post->getVisitsCount()
->since(Carbon::parse('01-01-2018')) // static
->uptoSubDays(5) // reactive
->count();
// Number of unique visits in the past two weeks
$post->getVisitsCount()
->sinceSubWeeks(2)
->unique()
->count();
<p>Total number of visits in the past two days: {{ $post->getVisitsCount()->sinceSubDays(2)->count() }}</p>
prefix: a unique prefix like: 'eloquent-visitable'
modelType: the class name with namespace
modelId: just the id
type: normal or unique
period: structured like this: '<sinceDate>|<uptoDate>'.
These dates are static or reactive.
<prefix>.<modelType>.<modelId>.<type>.<period>
I dont know What visitable_id is
Integrity constraint violation: 1048 Column 'visitable_id' cannot be null (SQL: insert into page-views (visitable_id, visitable_type, ip_address, updated_at, created_at) values (, App\Doctor, 139.190.64.77, 2018-01-11 09:01:32, 2018-01-11 09:01:32))
see here in the query above, it is taking visitable_id as empty value
please tell me what the issue is
Class 'App\Http\Controllers\Period' not found
$sortedPosts = Post::orderByViewsCount(Period::subDays(7))->get();
I need a POST weekly click list...
PS:My English is very poor, sorry
This package contains at this moment functionality for storing the page visits of an Eloquent model item. It also provides a special method for giving a page visit an expiry date. So the page views that the user has made before that time range will not be stored into the database.
But this allows users to make multiple page views of an Eloquent model. This means that they are not unique.
I'm thinking about tracking down the IP address of the visitors. So by using a simple filter, we're able to filter all the unique page views.
To give you access to this data, I'm maybe going to add new attributes. But I'm a little bit worried about the amount of attributes that this package adds to your Eloquent models. So to solve this problem, I got an idea.
Instead of one trait with all functionalities, we can split them up into multiple traits. This will give you the flexibility of choosing which features you need.
This issue is reserved for optimizing the speed of retrieving and storing page views.
I think that caching everything could improve the speed very much. This would be a nice addition, but the next thing to discuss is how should the page views be stored. Using a simple counter or storing every page view as a record (it currently works like this). But instead of counting all these page views on every request, the total page views could be stored in dedicated attribute on the model (or different table) as a JSON object.
There are two tables needed:
page-views
This table is only needed for users who wants to keep track of the historypage-views-counter
The page views table consists of every maked page view.
The page views counter table contains the same data as the main page-views
table, but is counted every day, week etc.
If page views are requested for a time range that's not available in the counters table, it will be counted and stored. This happens only the first time (unless these values are resetted or recounted).
Caching the values in the page-views-counter
table could improve the speed for a few milliseconds.
Ideas are very welcome!
Thank you for a great package. I installed it and everything seems works well, but I got ip_address is null in DB. Tried to check in HasPageViewCounter Trait and it's using $newView->ip_address = (new Request)->ip();
, I think it has problem with Laravel 5.5, could you check for help, please?
Thank you.
i have this function:
public function onTopComics()
{
//Get the comic with order by time
$comics = Comic::with(['volumes' => function($query) { $query->has('cover'); }])->has('chapters')->orderByViewsCount()->get();
//ajax time post
$time = post('time');
//sort by views
$sortedComics = $comics->sortByDesc(function ($comic) use ($time) {
switch($time) {
case '12hour':
return $comic->getViews(Period::subHours(12));
break;
case 'day':
return $comic->getViews(Period::pastDays(1));
break;
case 'week':
return $comic->getViews(Period::pastWeeks(1));
break;
case 'month':
return $comic->getViews(Period::pastMonths(1));
break;
}
});
return ['#rank-data' => $this->renderPartial('sidebar/top-comics', ['topComics' => $sortedComics, 'time' => $time])];
}
would this be the proper way to order the comics by views, I have tried this however im getting some mismatched ordering. Im not sure if its the ordering that's incorrect or its the view count retrieval that incorrect. (im using twig and made a function to use the period facade) so getting the views would looks something like this:
{{ comic.getViews(period.subHours(12)) }}
but when i check its incorrect, here is a screenshot of the ordering where its showing me an incorrect ordering:
I followed the instructions provided in the README file. However, when i want to add view with expiry date, laravel throws BadMethodCallException
Run
composer require cyrildewit/eloquent-viewable
Append below to providers array
CyrildeWit\EloquentViewable\EloquentViewableServiceProvider::class,
Publish Migrations:
php artisan vendor:publish --provider="CyrildeWit\EloquentViewable\EloquentViewableServiceProvider" --tag="migrations"
Run migration:
php artisan migrate
Publish config file.
php artisan vendor:publish --provider="CyrildeWit\EloquentViewable\EloquentViewableServiceProvider" --tag="config"
...
use CyrildeWit\EloquentViewable\Viewable;
class Project extends Model implements HasMedia, LikeableContract
{
use Sluggable;
use Taggable;
use HasMediaTrait;
use Likeable;
use Commentable;
use Viewable;
...
}
public function show($project_slug){
if ($project_slug === 'rp'){
$project = Project::inRandomOrder()->first();
}else{
$project = Project::where('slug', '=', $project_slug)->first();
}
$project->addViewWithExpiryDate(Carbon::now()->addHours(2));
return view('frontend.projects.show')
->with('page_title', 'Projeler - ' . $project->title)
->with('project', $project);
}
Expecting increment on the first page view and page view should not increase in case of refresh for 2 hours on the same session.
BadMethodCallException
is thrown for addViewWithExpiryDate
method. By the way addView()
method works as expected.
BadMethodCallException
Method Illuminate\Database\Query\Builder::addViewWithExpiryDate does not exist.
I get the error as below when I combine it with Laravel Scout MySQL Driver
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'page_visits' in 'where clause' (SQL: select count(*) as aggregate from
artikels where (
idLIKE %a% OR
jenisLIKE %a% OR
judulLIKE %a% OR
slugLIKE %a% OR
thumbnailLIKE %a% OR
deskripsiLIKE %a% OR
categories_idLIKE %a% OR
contentLIKE %a% OR
sourceLIKE %a% OR
statusLIKE %a% OR
users_idLIKE %a% OR
lockedLIKE %a% OR
created_atLIKE %a% OR
updated_atLIKE %a% OR
page_visitsLIKE %a% OR
page_visits_24hLIKE %a% OR
page_visits_7dLIKE %a% OR
page_visits_14dLIKE %a% OR
page_visits_formattedLIKE %a% OR
page_visits_24h_formattedLIKE %a% OR
page_visits_7d_formattedLIKE %a% OR
page_visits_14d_formatted LIKE %a%))
First it recordas the ip, then the cookie (like 2 diff visits)
and the getviews() always returns 2 (?)
i don't know if i'm doing something wrong
Has been removed? Only addView()
seems to be available.
Add steps of README
Is addView()
doing the same and is addViewWithExpiryDate()
not needed anymore?
Doesn't exists.
Hi,
I have an issue with your module. Whenever a composer dump-autoload
is triggered, I have an error as composer ignored your project.
Symfony\Component\Debug\Exception\FatalThrowableError thrown with message "Class 'CyrildeWit\PageViewCounter\PageViewCounterServiceProvider' not found"
Stacktrace:
#1 Symfony\Component\Debug\Exception\FatalThrowableError in /laravel/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php:208
#0 {main} in /laravel/public/index.php:0
I can fix it with a
composer dump-autoload -o
In autoload_psr4.php, I have:
'CyrildeWit\\PageViewCounter\\' => array($vendorDir . '/cyrildewit/laravel-page-view-counter/src'),
in installed.json:
{
"name": "cyrildewit/laravel-page-view-counter",
"version": "v1.0.4",
"version_normalized": "1.0.4.0",
"source": {
"type": "git",
"url": "https://github.com/cyrildewit/laravel-page-view-counter.git",
"reference": "ae4ec30fae16c9ea567e68897d528a59221adcc2"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/cyrildewit/laravel-page-view-counter/zipball/ae4ec30fae16c9ea567e68897d528a59221adcc2",
"reference": "ae4ec30fae16c9ea567e68897d528a59221adcc2",
"shasum": ""
},
"require": {
"nesbot/carbon": "^1.22"
},
"require-dev": {
"orchestra/testbench": "^3.4",
"phpunit/phpunit": "~5.7.0"
},
"time": "2018-02-20T15:56:47+00:00",
"type": "library",
"extra": {
"laravel": {
"providers": [
"CyrildeWit\\PageViewCounter\\PageViewCounterServiceProvider"
]
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"CyrildeWit\\PageViewCounter\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Cyril de Wit",
"email": "[email protected]",
"homepage": "http://cyrildewit.nl",
"role": "Developer"
}
],
"description": "Simple package for storing page views of Eloquent models into the database",
"homepage": "https://github.com/cyrildewit/laravel-page-view-counter",
"keywords": [
"cyrildewit",
"hits",
"laravel",
"model",
"pageviews",
"visits"
]
},
in autoload_static.php:
'C' =>
array (
'CyrildeWit\\PageViewCounter\\' => 27,
'Cron\\' => 5,
'Carbon\\' => 7,
),
'CyrildeWit\\PageViewCounter\\' =>
array (
0 => __DIR__ . '/..' . '/cyrildewit/laravel-page-view-counter/src',
),
With the optimized autoload, I have new entries in autoload_classmap.php
'CyrildeWit\\PageViewCounter\\Contracts\\PageView' => $vendorDir . '/cyrildewit/laravel-page-view-counter/src/PageViewCounter/Contracts/PageView.php',
'CyrildeWit\\PageViewCounter\\Helpers\\DateTransformer' => $vendorDir . '/cyrildewit/laravel-page-view-counter/src/PageViewCounter/Helpers/DateTransformer.php',
'CyrildeWit\\PageViewCounter\\Helpers\\SessionHistory' => $vendorDir . '/cyrildewit/laravel-page-view-counter/src/PageViewCounter/Helpers/SessionHistory.php',
'CyrildeWit\\PageViewCounter\\Models\\PageView' => $vendorDir . '/cyrildewit/laravel-page-view-counter/src/PageViewCounter/Models/PageView.php',
'CyrildeWit\\PageViewCounter\\PageViewCounterServiceProvider' => $vendorDir . '/cyrildewit/laravel-page-view-counter/src/PageViewCounter/PageViewCounterServiceProvider.php',
'CyrildeWit\\PageViewCounter\\Traits\\HasPageViewCounter' => $vendorDir . '/cyrildewit/laravel-page-view-counter/src/PageViewCounter/Traits/HasPageViewCounter.php',
Thanks!
This does not happen with any other dependencies I have installed.
composer dump-autoload
On my local machine I have installed it and migration with the view table is done successfully but calling the model on my post details controller function as below.
public function getPostDetail(Post $post){
$post->addView();
}
giving me error of viewable_id null so not able to store the views in the database. please check below refer for the error.
Refer: http://prntscr.com/k4pjcn
I have an API that returns a post and I want to implement the eloquent-viewable package but it seems it's not working on the API side whatever I do even when I try to return the API from browser, anyway when I'm testing it on browser on a web routes it's working great but the same web route when hit from postman doesn't count anything, I have disabled cache in the config file too.
[What you expected to happen]
[What actually happened]
Rather than flooding the database with new visit entries why not create a new column that gets incremented, every time someone with the same IP visits the site, the total pageviews would just count sum of all the increments all ips have for that model and the unique views would count just for that row for each visited IP. This way you wont end up with a completely flooded database filled with records.
when I put in a remote connection for mysql, the queuing works and doesn't work at the same time. What I mean is that the connection is made, and the view gets sent to the remote database after the delay, so everything works there. It's just that after it gets sent Horizon shows
InvalidArgumentException: Database [mysql_offload] not configured.
but that connection "is" configured and everything works.
It seems that sortBy
not working properly with paginate
when trying this
$scholarships = Scholarship::with(
'city.country'
)->paginate(12)->sortBy('page_views');
it throwing method not exist exception
ErrorException Method Illuminate\Database\Eloquent\Collection::links does not exist.
I have no idea why this is happening, but I'm currently using OctoberCMS it has a relation called "attachOne" where it allows me to attach an image to the model via a relation (its basically a morph). What happens is that if it has no background and you visit the page the view will be counted twice. However if it does have a background, the view will be counted once. I'm not sure why this is happening.
I need to know how can I use this package for API as well.
Because there are web services in my project and they are also showing total views for each item and I have to store views from that service as well.
can I use this package for storing and retrieving page views as well for JSON response?
I'm about to add this package to my project, but wondered how this would scale with large numbers of views? Do queries become very slow when thousands of records have been saved to the database?
Anyone have experience of using this with MySQL?
When trying to use addVisitThatExpiresAt I get an exception error.
Argument 1 passed to Cyrildewit\PageVisitsCounter\Classes\SessionHistory::fromCamelCaseToDashes() must be an instance of Cyrildewit\PageVisitsCounter\Classes\string, string given
The main goals are:
Eloquent Viewable
Branch: 2.0
Migration possible: yes
HTTP_DNT
header.countViews()
in ViewableService.php
.Since every page view is stored as a seperate entity in the database, counting the views can be a time consuming task. So instead, we could cache views counts in the cache to reduce the amount of queries.
While the whole idea of caching sounds quite simple, it is harder than I thought. The way I would cache views counts is saving the number of views under a unique key that's created based upon the since date, upto date and if the views should be unique. The structure of this key is: <package prefix>.counts.<model type>.<model id>.<request type: normal | unique>.<request period: <since?>|<upto?>>
.
Segment name | Description |
---|---|
package prefix | Default: 'cyrildewit.eloquent-viewable'. This can be changed in the config file. |
model type | The class namespace of the viewable model |
model id | The primary id of the viewable model |
request type | Default: 'normal'. Unique views: 'unique' |
request period | The structure of this part is: '<since?>|<upto?>'. If the given date is reactive (like past 3 days or past 2 weeks) they will not be stored as a date string |
Old
$article->getPageViews();
$article->getUniquePageViews();
$article->getPageViewsFrom($sinceDate);
$article->getUniquePageViewsFrom($sinceDate);
$article->getPageViewsBefore($uptoDate);
$article->getUniquePageViewsBefore($uptoDate);
$article->getPageViewsBetween($sinceDate, $uptoDate);
$article->getUniquePageViewsBetween($sinceDate, $uptoDate);
New
$article->getViews();
$article->getUniqueViewsSince();
$article->getViewsSince($sinceDate);
$article->getUniqueViewsSince($sinceDate);
$article->getViewsUpto($uptoDate);
$article->getUniqueViewsUpto($uptoDate);
$article->getViewsBetween($sinceDate, $uptoDate);
$article->getUniqueViewsBetween($sinceDate, $uptoDate);
// New
$article->getViewsOfPastSeconds();
$article->getViewsOfPastMinutes();
$article->getViewsOfPastDays();
$article->getViewsOfPastWeeks();
$article->getViewsOfPastMonths();
$article->getViewsOfPastYears();
CyrildeWit\EloquentViewable\Traits\Viewable
)CyrildeWit\EloquentViewable\Services\ViewableService
)CyrildeWit\EloquentViewable\Models\View
)CyrildeWit\EloquentViewable\Observers\ViewableObserver
)CyrildeWit\EloquentViewable\Contracts\CrawlerDetector
)CyrildeWit\EloquentViewable\Support\Period
)CyrildeWit\EloquentViewable\ViewTracker
)Hi,
Do I have need any controller method in order to save data or no?
these codes
// Return total visits of the article
$article->page_visits
$article->page_visits_formatted
// Return total visits of last 24 hours
$article->page_visits_24h
// Store a new visit into the database
$article->addVisit();
// Store a new visit into the database with an expiry date
$article->addVisitThatExpiresAt(Carbon::now()->addHours(3));
are just to show visits numbers or what exactly? (i mean frontend such as this post visited 1.000 times
like that?)
Thanks.
I am unable to install the package. I get this error when I run php artisan migrate after doing the first two steps:
In Macroable.php line 74:
Method varchar does not exist.
I used getUniquePageViews() but doing multiple recordings my SQL on localhost
image -> http://prntscr.com/j6h4in
image -> http://prntscr.com/j6h52v
// Store a new page view into the database with an expiry date
$article->addPageViewThatExpiresAt(Carbon::now()->addHours(3));
Have you removed this? or Is there a different way of doing it?
[What you expected to happen]
[What actually happened]
Im not sure why but changing my cache to redis seems to be cause some typehinting errors:
Symfony\Component\Debug\Exception\FatalThrowableError: Type error: Return value of Tera\Comic\Models\Comic::getViews() must be of the type integer, string returned in /home/caligula/public_html/vendor/cyrildewit/laravel-page-view-counter/src/Viewable.php:56
public function getViews($period = null): int
to
public function getViews($period = null)
when i remove the typehint from "all" the functions then everything works fine otherwise i just use memcached again. It also works if i disable caching in the viewable config
Change cache to redis
This happens when I clear my Cache and Cookies from the browser and refresh the browser.
I get the error Integrity Violation Column 'visitor' cannot be null
.
But if I refresh again, It works.
Could it be that the cookie is not being initiated? How can I fix this?
Support for mongodb plugin for laravel
https://github.com/jenssegers/laravel-mongodb
benifits on using mongodb over mysql is no need to make annoying migrations just add the data with eloquent as you go.
Counter is no longer working? i have had no problems until the past couple of days when the view count wont exceed 1 ?
The idea is:
The main trait: HasPageViewCounter
will contain all the main functionality. Things like relationships and core functions to retrieve the page view count will be placed here.
If the developer wants to use the available attributes, he or she can add the needed traits to his model.
This avoids unnecessary attributes in a model.
It is not taking lots of other fields like title,body and others. It is working fine if i comment out the below
use HasPageVisitsCounter;
error:
SQLSTATE[HY000]: General error: 1364 Field 'category_id' doesn't have a default value (SQL: insert into articles
(updated_at
, created_at
) values (2017-08-16 12:05:23, 2017-08-16 12:05:23))
controller:
public function store(Request $request)
{
$input = $request->all();
$input['slug'] = str_slug($request->input('title'), '-');
$article = \App\Article::create($input);
return redirect('master/articles');
}
Article Model:
use HasPageVisitsCounter;
protected $fillable = [
'category_id','author','title','body', 'slug','excerpt'
];
public function category() {
return $this->belongsTo('App\Category');
}
Do not know where the issue is.
don't work ..
$article->retrievePageVisitsFrom(Carbon::now()->subWeeks(2));
Your application works like charm, thank you!
The issue i'm facing is when I export my data as CSV
it is included page views info (if i'm not mistake 5 columns will add to my CSV file)
Question:
How can I ban (forbid) your package of having access to my database export?
Hi, first thank you for sharing this awesome package!
I tried to sort my model (Activity
) by page_views
by getting this error:
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Call to a member function addPageViewThatExpiresAt() on null
public function sortByPageView()
{
// $acts = Activity::all()->sortByDesc(function ($act){
// return $act->getPageViews();
// });
$acts = Activity::all()->sortBy('page_views');
return view('activities.index')->with('activities', $acts);
}
And the addPageViewThatExpiresAt()
is called at
public function show($id)
{
$act = Activity::find($id);
$act->addPageViewThatExpiresAt(Carbon::now()->addHours(2));
return view('activities.show')->with('act', $act);
}
edit: The show
function works without any problem, but I cannot sort by the page_views
.
And I have did at Activity
use HasPageViewCounter;
protected $appends = ['page_views'];
public function getPageViewsAttribute()
{
return $this->getPageViews();
}
Any helps? Thank you!
I think it's useful to create a section in the readme about how the views are stored in the database, how they are counted and what happens when we turn caching on. This section will also explain why the current version stores each view as a seperate record.
Hi Cryril,
I hope you are doing good. Thank you for adding the viewThatExpiresAt trait in the v2.0 but my question here is what is the difference between v2.0 and v1.0 and how do I migrate my older v1.0 data to new v2.0 as the table structure is different this time?
I'm following the tutorial.
But in cmd I get the following answer:
Nothing to publish for tag [migrations].
C:\Users\projectl>composer require cyrildewit/laravel-page-view-counter
Using version ^1.0 for cyrildewit/laravel-page-view-counter
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
- Installing cyrildewit/laravel-page-view-counter (v1.0.5): Downloading (100%)
Writing lock file
Generating autoload files
> Illuminate\Foundation\ComposerScripts::postUpdate
> php artisan optimize
Generating optimized class loader
The compiled class file has been removed.
C:\Users\projectl>php artisan vendor:publish --provider="CyrildeWit\PageViewCounter\PageViewCounterServiceProvider" --tag="migrations"
Nothing to publish for tag [migrations].
In config/app
I already inserted the provider
CyrildeWit\PageViewCounter\PageViewCounterServiceProvider::class,
When this package is used https://github.com/spatie/laravel-responsecache to cache entire response (for speed), page views are only recorded for the first time. as the next request will provide response from the cache, the page views are not recorded. Is there any workaround this?
I know it does use cookies but every time i refresh the post page and go back, it is added as a view to the db. The expected behavior is that the user should only be able to view one single post once. Unless the cookie is deleted and browser is refreshed. In that case, a new view will be added. Or am I doing something wrong here?
i removed your package, but i need to keep view.php in config, otherwise i got this error 👍
Type error: Argument 2 passed to Illuminate\View\FileViewFinder::__construct() must be of the type array, null given, called in .../vendor/laravel/framework/src/Illuminate/View/ViewServiceProvider.php on line 64
.
How can i delete this file safely?
When using the package on my Post model, I am getting an error when inserting/creating a post.
One of the fields i am inserting is 'user_id' it's value is Auth::user()->id.
I get an error telling me 'user_id' has no default value, not sure how or why this is happening.
It's not an issue with my Model because if i remove the trait from the model my insert/create works just fine no issues.
I should also mention this seems to be an issue with the trait and using Auth::user()->id.
If i hard code a value e.g. $user_id = "1"; the insert works.
if i use $user_id = Auth::user()->id; I get the error
Also if i dd(Auth::user()->id) within my create method, I return the correct value.
Issue seems to happen as soon as the create (database action) is hit.
Any help would be very much appreciated.
First off, love the package and what you’ve done with it so far.
The issue for me is that I have 2 variables which handles 2 kinds of views. One of the route is as follows:
Route:get(‘post/{category}/{id}’, ‘SomeController@Display’);
And here is the second route:
Route:get(‘post/{category}/{subcategory}/{id}’, ‘SomeOth rController@Display’)
As you can see, I have one controller and route which displays post with category. The other route and controller is for sub category. They both come from the same model. They also have different where clauses.
So my question is, in this case, should I use the same method as in the docs? I mean, should I use the $post->addView(); on both the controller display method?
And if so, how can I get the count of these two separately? One is with category. The other one with sub category.
Lastly, how can I order these two by whats the most popular posts. The issue for me is that I am using a category and subcategory separately. So if I want to even count the views, I would want to count it for category and subcategory. Those two are having 2 routes and two methods. That’s my confusion.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.