Get products with number of orders in Laravel

You can get the products with number of orders in Laravel. Sometimes you have to get the number of orders placed for the products, in that case, this code snippet will help you to find out the solution for you.

Answers 3
  • Return products with number of orders using count of nested relationship data

    $products = Product::all(); 
    $productsArr = $products->map(function (Product $product){     
        $productObj = $product->toArray();     
        $productObj['orders_count'] = $product->orders()->count();     
        return $productObj; 
    });
    
    0

    This code snippet will help you to get the total number of orders (records of relationship data)  with Product. In this code there is a map method which get the count of orders form the relationship while iterating product model data. 

    You have to create the orders method in Product model.

    app\Models\Product.php

    public function orders(){
        return $this->hasMany('App\Models\Order');
    }
  • Return products with number of orders using eager load relationship

    $products = Product::with('orders')->get(); 
    $productsArr = $products->map(function (Product $product){
        $productObj = $product->toArray();
        $productObj['orders_count'] = $product->orders->count();
        return $productObj; 
    });
    
    0

    It helps you to get the total number of orders (records of relationship data) with Product. In this code there is a map method which get the count of orders form the relationship while iterating products.

    Here we have use eager load relationship which helps you to reduce the number of query while getting data from table.

  • Return products with number of orders using withCount() function

    $products = Product::withCount('orders')->get();
    $productsArr = $products->map(function (Product $product){     
        $productObj = $product->toArray();
        $productObj['orders_count'] = $product ->getAttribute('orders_count');     
        return $productObj; 
    });
    
    0

    This code snippet will help you to get the total number of orders (records of relationship data) with product. There is a map method which get the count of orders form the relationship data while iterating products.

  • Back to code snippet queries related laravel