Paulo Freitas Paulo Freitas - 1 month ago 16
PHP Question

Laravel: Tracking page views

I'm trying to implement a very simple page tracking system with Laravel, just to know which pages are most accessed.

At first I thought of create a table with access date, request URL (from

Request::path()
) and user id, as simple as that.

But I'd have to show page titles on reports, and for that I need some way to translate the request URI to its page title. Any ideas for that? Is there a better way to accomplish this?

Currently I set page titles from Blade view files, through
@section('title', ...)
.

Thank you in advance!

Answer

You can use Google Analytics to show pretty and very efficient reports. With the API, you can also customize the reports and (for example) show the pages titles.

If you want to develop it by yourself, I think that the best solution is to write an after filter that can be called after each page loading. One way of setting the title, in this case, is to use flash session variable (http://laravel.com/docs/session#flash-data) :

// routes.php
Route::group(array('after' => 'log'), function()
{
    Route::get('users', 'UserController@index');
}

// filters.php
Route::filter('log', function() {
    Log::create(array('title' => Session::get('title'), '...' => '...'));
}

// UserController.php
public function index()
{
    Session::flash('title', 'Users Page');
    // ...
}


// layout.blade.php
<head>
    <title>{{ Session::get('title') }}</title>
    ...