Count post view
Created 4 months ago by wakanda

What is your approach for add a counter 'hits' on view post module :

  • Add custom field 'hits' to module post + Add middleware on route with post entry update ?
  • Add custom field 'hits' to module post + Extend Eloquent model ?
  • Add custom field 'hits' to module post + Form Handler update by route ?
  • Others ?
ryanthompson  —  2 weeks ago

Funny we do this in the forum module which I have just updated and am digging through older un-replied discussions 😛

We use a view_count column and update the count inline in the controller using a command.

Be sure to wrap your query in withoutEvents like this:

<?php namespace Anomaly\ForumModule\Discussion\Command;

use Anomaly\ForumModule\Discussion\Contract\DiscussionInterface;
use Anomaly\ForumModule\Discussion\Contract\DiscussionRepositoryInterface;
use Anomaly\Streams\Platform\Model\EloquentModel;

class IncrementViewCount
{

    /**
     * @var DiscussionInterface|EloquentModel
     */
    protected $discussion;

    public function __construct(DiscussionInterface $discussion)
    {
        $this->discussion = $discussion;
    }

    public function handle(DiscussionRepositoryInterface $discussions)
    {
        $discussions->withoutEvents(function() use ($discussions) {
            $discussions->save($this->discussion->setAttribute('view_count', $this->discussion->getViewCount() + 1));
        });
    }
}