php - get order products categories in laravel

I have four tables Order, Category, Product, Order_Product

each product belongs to a category each order has many products

i save the order products in order_product table,

now in orderResource i want to have number of order->products in each category so OrderResource should have

data 
[
{
 category_name: 'something',
productsCount: 3,
},
{
category_name: 'somethingelse',
productsCount: 2
}
]

how to do so ?

Answer

Solution:

So you want to get products from an order, and group the products by category and count the number of products in a category.

$orders = Order::with(['products' => function($query) {
    $query->groupBy('category_id')
        ->select(DB::raw('count(*) AS productsCount'), 'category_id')
        ->with('category');
}])
->get();

foreach($orders as $order) {
    foreach($order->products as $product) {
        $product->productsCount;
        $product->category->name;
    }
}

Source