@prince69 You can try this
$posts = Product::select(
'id as product_id',
'name as product_name',
DB::raw('COUNT(*) as item_count'), // Count of items in the group
DB::raw('SUM(price) as total_amount') // Sum of prices in the group
)
->groupBy(DB::raw('IFNULL(category_id, id)')) // Group by category_id if not null, otherwise by id
->get();