PHP code example of quankim / laravel-counter-cache
1. Go to this page and download the library: Download quankim/laravel-counter-cache 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/ */
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\Comment;
class Product extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
public function ratingAverage()
{
return round($this->comments()->avg('rating_value'), 1);
}
}
namespace App\Models;
use QuanKim\LaravelCounterCache\Traits\CounterCache;
use Illuminate\Database\Eloquent\Model;
use App\Models\Product;
class Comment extends Model
{
use CounterCache;
public $counterCacheOptions = [
'product' => [
'comments_count' => [],
'rating_average' => [
'method' => 'ratingAverage',
],
],
];
public function product()
{
return $this->belongsTo(Product::class);
}
}
use CounterCache {
boot as preBoot;
}
protected static function boot()
{
self::preBoot();
// ...
}