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/ */

    

quankim / laravel-counter-cache example snippets


Schema::create('products', function (Blueprint $table) {
      $table->increments('id');
      $table->string('name');
      $table->integer('comments_count')->default(0);
      $table->float('rating_average', 15, 1)->nullable();
      $table->timestamps();
  });

Schema::create('comments', function (Blueprint $table) {
      $table->increments('id');
      $table->integer('product_id');
      $table->string('content');
      $table->integer('rating_value')->nullable();
      $table->timestamps();
  });


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();

    // ...
}

public $counterCacheOptions = [
    'product' => [
        'comments_count' => [],
        'rating_average' => [
            'method' => 'ratingAverage',
            'conditions' => [
                'is_publish' => true,
            ],
        ],
    ],
];