Search code examples
laraveleloquentmany-to-manylaravel-query-builder

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

Solution

  • Maybe something like this would work

    $topfive = Order::with('products')->get()->sortBy(function($order) {
        return $order->products->count();
    })->take(5);
    

    Here you get the orders that have any products, make a collection out of it, sort by the number of products each order has and take the top 5. I hope this is what you meant by "top 5". If not tell me and ill fix the query.

    EDIT 1

    Since you need the products most frequented heres the reverse query

    $topfive = Product::with('orders')->get()->sortBy(function($product) {
            return $product->orders->count();
        })->take(5);