Hits or Views Counter Using Laravel and Redis

2515 views

Description:

Thinking of implementing hits/views counter in your apps? You will love this! :)

Resource: https://github.com/basco-johnkevin/laravelsnippets/blob/master/app/models/Snippet.php

// add this in your routes.php file or in a service provider
$app->singleton('redis', function()
{
    return Redis::connection();
});


// Create a model with the following methods
// model
class Snippet extends Eloquent {

    /**
     * Hits eloquent accessor
     *
     * @return string
     */
    public function getHitsAttribute()
    {
        $redis = App::make('redis');
        return $redis->zScore('hits', $this->id);
    }

    /**
     * Determine if Snippet has hits/views
     *
     * @return boolean
     */
    public function hasHits()
    {
        return $this->hits ? true : false;
    }

    /**
     * Increment hits count
     */
    public function incrementHits()
    {
        $redis = App::make('redis');
        $redis->zIncrBy('hits', 1, $this->id);
    }

}

// then you can do the following:

// increment hits count
$snippet->incrementHits();

// get hits count
$snippet->hits;

// check if the current model has hits
if ($snippet->hasHits()) 
{
	// do something :)
}

Submitted 11 months ago.
Updated 11 minutes ago.

comments powered by Disqus

Want to help with the site? We accept pull requests! Find us on Github