Laravel top sale product function

I have many to many relation ship between Product and order through order_details,

how i can get top 5 sale product?

Product:

public function orders()
    {
        return $this->belongsToMany(Order::class, 'order_details');
    }

Order:

  public function products()
    {
        return $this->belongsToMany(Product::class, 'order_details')->withPivot(['quantity', 'sale_price']);
    }

Pivot table:

public function up()
{
    Schema::create('order_details', function (Blueprint $table) {
        $table->id();
        $table->foreignId('order_id');
        $table->foreign('order_id')
            ->on('orders')
            ->references('id')->onDelete('cascade');
        $table->foreignId('product_id');
        $table->foreign('product_id')
            ->on('products')
            ->references('id')->onDelete('cascade');
        $table->integer('quantity');
        $table->decimal('sale_price', 10, 4);
        $table->timestamps();
    });
}

Source: Laravel

Leave a Reply