Update view/visit counter in laravel database
To update the view counter in Laravel database, you can follow these steps:
Step 1:
Create a migration for the table (if not already created) that will hold the view counter. For example, you can create a migration named “add_view_count_to_articles_table” that will add a “view_count” column to the “articles” table.
php artisan make:migration add_view_count_to_articles_table --table=articles
Step 2:
In the migration file, add the following code to create the “view_count” column:
public function up()
{
Schema::table('articles', function (Blueprint $table) {
$table->unsignedInteger('view_count')->default(0);
});
}
Step 3:
Run the migration to update the database schema.
php artisan migrate
Step 4:
In the controller method that displays the article, increment the “view_count” column and save the updated record to the database:
public function show($id)
{
$article = Article::findOrFail($id);
$article->view_count++;
$article->save();
return view('articles.show', compact('article'));
}
Step 5:
Display the view count in your view:
<p>View count: {{ $article->view_count }}</p>
That’s it! Now the view count for each article will be tracked and updated in the database.