Skip to content

Instantly share code, notes, and snippets.

@JSila
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JSila/36277262723bafe0c439 to your computer and use it in GitHub Desktop.
Save JSila/36277262723bafe0c439 to your computer and use it in GitHub Desktop.
Laravel: Count visits (visit of movie resource in this case)
<?php namespace App\Http\Middleware;
use App\Movie;
use Carbon\Carbon;
use Closure;
use Illuminate\Http\Response;
use Illuminate\Session\Store;
class CountMovieVisits {
/**
* @var Store
*/
protected $session;
/**
* @var Movie
*/
protected $movie;
/**
* @param Store $session
* @param Movie $movie
*/
function __construct(Store $session, Movie $movie)
{
$this->session = $session;
$this->movie = $movie;
}
/**
* Handle an incoming request.
* Checks if we are on page for showing single resource and
* increment its visit number if timestamp is later than 2 hours.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return Response
*/
public function handle($request, Closure $next)
{
$slug = $request->route('movies');
$timestamp = $this->session->get('visits.' . $slug);
if ( ! $this->isRecentVisit($timestamp))
{
$this->movie->whereSlug($slug)->first()->increment('visits');
$this->session->put('visits.' . $slug, Carbon::now());
}
return $next($request);
}
/**
* Checks if timestamp is earlier than now minus 2 hours.
*
* @param Carbon $timestamp
* @return bool
*/
private function isRecentVisit($timestamp)
{
$earlierTimestamp = Carbon::now()->subHours(2);
return ! is_null($timestamp) && $timestamp->gt($earlierTimestamp);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment