How to count number of clicks on link in laravel?

by cali_green , in category: PHP Frameworks , 11 days ago

How to count number of clicks on link in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 10 days ago

@cali_green 

There are several ways to count the number of clicks on a link in Laravel. One common way is to create a table in your database to store the click data, and then increment a counter in that table each time the link is clicked.


Here is a step-by-step guide on how to achieve this:

  1. Create a new migration to create a table to store the click data. Run the following command in your terminal:
1
php artisan make:migration create_clicks_table


  1. Open the newly created migration file (located in database/migrations) and add the following code to create the clicks table:
1
2
3
4
5
6
Schema::create('clicks', function (Blueprint $table) {
    $table->id();
    $table->string('link');
    $table->integer('count')->default(0);
    $table->timestamps();
});


  1. Run the migration to create the clicks table in your database:
1
php artisan migrate


  1. Create a route in your routes/web.php file to handle the click functionality:
1
Route::get('/click/{id}', 'ClickController@click');


  1. Create a controller called ClickController using the following command:
1
php artisan make:controller ClickController


  1. Open the ClickController.php file (located in app/Http/Controllers) and add the following code to handle the click logic:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppClick;

class ClickController extends Controller
{
    public function click($id)
    {
        $click = Click::find($id);
        $click->count++;
        $click->save();
        
        return redirect($click->link);
    }
}


  1. When displaying the link in your views, make sure to pass the id of the click record as a parameter in the link URL. For example:
1
<a href="{{ route('click', ['id' => $click->id]) }}">Click me</a>


  1. Every time the link is clicked, the count column in the clicks table will be incremented by one. You can then retrieve this data to display the number of clicks on the link.


By following these steps, you can easily count the number of clicks on a link in Laravel.