1. Go to this page and download the library: Download turahe/laravel-counters library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
turahe / laravel-counters example snippets
use Turahe\Counters\Models\Counter;
// Create a counter for page views
Counter::create([
'key' => 'page_views',
'name' => 'Page Views',
'initial_value' => 0,
'step' => 1
]);
use Turahe\Counters\Traits\HasCounter;
class Post extends Model
{
use HasCounter;
// Your model code...
}
// In your controller
public function show(Post $post)
{
$post->incrementCounter('page_views');
return view('posts.show', compact('post'));
}
use Turahe\Counters\Facades\Counters;
// Track total downloads
Counters::increment('total_downloads');
use Turahe\Counters\Traits\HasCounter;
class Post extends Model
{
use HasCounter;
// Your model code...
}
// Add a counter to a model
$post->addCounter('views');
// Get counter value
$views = $post->getCounterValue('views');
// Increment counter
$post->incrementCounter('views');
// Decrement counter
$post->decrementCounter('views', 2); // Decrement by 2
// Reset counter to initial value
$post->resetCounter('views');
// Remove counter from model
$post->removeCounter('views');
// Check if model has counter
if ($post->hasCounter('views')) {
// Do something
}
use Turahe\Counters\Facades\Counters;
// Create a counter
Counters::create('total_downloads', 'Total Downloads', 0, 1);
// Get counter value
$downloads = Counters::getValue('total_downloads');
// Increment counter
Counters::increment('total_downloads');
// Decrement counter
Counters::decrement('total_downloads', 2);
// Set specific value
Counters::setValue('total_downloads', 100);
// Reset to initial value
Counters::reset('total_downloads');
// Only increment if user doesn't have cookie
Counters::incrementIfNotHasCookies('daily_visitors');
Counters::decrementIfNotHasCookies('available_slots');
// Create the counter first
Counter::create([
'key' => 'page_views',
'name' => 'Page Views',
'initial_value' => 0,
'step' => 1
]);
// Then use it
$post->incrementCounter('page_views');
// Good
$post->incrementCounter('article_views');
$user->incrementCounter('login_count');
// Avoid generic names
$post->incrementCounter('count');
if ($post->hasCounter('views')) {
$post->incrementCounter('views');
} else {
$post->addCounter('views');
$post->incrementCounter('views');
}
// This might fail if counter doesn't exist
$post->incrementCounter('undefined_counter');
// Better approach
$post->addCounter('new_counter');
$post->incrementCounter('new_counter');