Laravel View Counter

Laravel View Counter

To implement a view counter in Laravel, you can follow these steps:

1. Create a migration for the view counter table using the command:
php artisan make:migration create_view_counters_table --create=view_counters
This will create a migration file in the database/migrations directory.

2. Open the migration file and define the necessary fields for your view counter table. For example, you may want to store the ID of the viewed item and the total views count. Here’s an example migration file:

 
      use Illuminate\Database\Migrations\Migration;
      use Illuminate\Database\Schema\Blueprint;
      use Illuminate\Support\Facades\Schema;

      class CreateViewCountersTable extends Migration
      {
          /**
           * Run the migrations.
           *
           * @return void
           */
          public function up()
          {
              Schema::create('view_counters', function (Blueprint $table) {
                  $table->id();
                  $table->unsignedBigInteger('item_id');
                  $table->integer('views')->default(0);
                  $table->timestamps();

                  $table->foreign('item_id')->references('id')->on('items')->onDelete('cascade');
              });
          }

          /**
           * Reverse the migrations.
           *
           * @return void
           */
          public function down()
          {
              Schema::dropIfExists('view_counters');
          }
      }
    

3. Run the migration to create the view_counters table in your database using the command:
php artisan migrate

4. Create a ViewCounter model using the command:
php artisan make:model ViewCounter
This will create a model file in the app/Models directory.

5. Open the ViewCounter model and define the relationships and increment views function. Here’s an example:


      namespace App\Models;

      use Illuminate\Database\Eloquent\Factories\HasFactory;
      use Illuminate\Database\Eloquent\Model;

      class ViewCounter extends Model
      {
          use HasFactory;

          protected $fillable = ['item_id', 'views'];

          public function item()
          {
              return $this->belongsTo(Item::class);
          }

          public static function incrementViews($item)
          {
              $viewCounter = self::firstOrNew(['item_id' => $item->id]);
              $viewCounter->views++;
              $viewCounter->save();
          }
      }
    

6. Next, in your item view controller or route closure, call the incrementViews() function of the ViewCounter model to increment the views count for the item. For example:


      use App\Models\ViewCounter;

      function show(Item $item)
      {
          ViewCounter::incrementViews($item);

          return view('items.show', compact('item'));
      }
    

7. Finally, in your item view file, you can display the views count using the value stored in the view_counters table. For example:


      

Views: {{ $item->viewCounter->views }}

This way, every time an item view is accessed, the view counter will be incremented and the updated views count will be displayed in your item view.

Note: In the above examples, I assumed you have an “items” table with an “id” field. Adjust the code according to your specific table and field names.

Read more

Leave a comment