Reputation: 65
I spent couple of hours for searching visitor tracker and click counter usage for laravel 5.2 . But I didn't found the best. If you know please point me
Upvotes: 1
Views: 3987
Reputation: 1723
⚠️ Disclaimer: while those methods technically work, visitor and click tracking would probably be implemented in a different way today in 2023.
I would record visits directly in the database in the corresponding controller. This is the most easy and convenient way to track page views. It saves the unique visitor session ID and the current page to the database. Here is an example:
class PageController extends Controller
{
public function index()
{
\DB::table('visitors')->create([
'visitor' => session()->getId(),
'page' => 'index',
]);
return view('pages.index');
}
}
I would work with Javascript and an API endpoint that receives the data but this is a little bit more complicated.
I didn't tested this code but it should work this way. If it's not working correctly please add a comment.
Actual link in your HTML
The link needs the onclick attribute. Listening to link clicks with JS only didn't worked for me, maybe the delay between the click and the event handling is too large to call the function.
<a href="some-url-here" onclick="trackClick(this)">
Javascript
The function trackClick
is called when a user clicks the above link and pushes the data via POST to the API endpoint of your application. Don't forget to replace csrf_token
with the actual token of your application.
function trackClick(link) {
$.post({
url: '/api/track-click',
data: {
'_token': csrf_token,
'link_target':$(link).attr('src')
}
});
}
Route
This would be the corresponding route to your controller:
Route::post('api/track-click', 'ApiController@addClick');
API Controller
The controller takes the POST data and simply saves the link target to the database. You could extend this function to check if the target is internal or external. It's just a starting point for now.
class ApiController extends Controller
{
public function addClick(Request $request)
{
$click = \DB::table('clicks')->where([
'visitor' => session()->getId(),
'link' => $request->get('link_target'),
])->first();
if ($click) {
$click->increment('count');
} else {
\DB::table('clicks')->create(array(
'visitor' => session()->getId(),
'link' => $request->get('link_target'),
'count' => 1
));
}
}
}
Upvotes: 4