Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

qTylok's avatar

Add data to the same collection without it appearing in the query

Hi, I have the next query

$products = collect();
$product = ProductFlat::leftJoin('product_images', 'product_flat.product_id', '=', 'product_images.product_id')
                        ->select('product_flat.product_id as id','product_flat.name', 'product_flat.url_key as slug', 'product_images.path as image','product_flat.price')
                        ->addSelect(DB::raw("0 as total"))
                        ->addSelect(DB::raw("0 as quantity"))
                        ->addSelect(DB::raw("'$inStock' as in_stock"))
                        ->where('product_flat.name', $orderedProduct)->get();
$products->push($product);

And I would like to add two more variables to the collection

$totalQty = $productMain->getTypeInstance()->totalQuantity();
            $stockStatus = $productMain->getTypeInstance()->checkStock();

How can I add the two variables for each product?

0 likes
7 replies
tykus's avatar

There are no variables in a Collection; do you mean that each item in the Collection should get a new property? Or, do you want this additional data at the top-level (siblings of the Products)?

qTylok's avatar

@tykus I would like the products collection to receive these 2 properties but not to be outside the 'collection'

drewdan's avatar

You could map the collection and add the extra data each time you iterate through it.

https://laravel.com/docs/8.x/collections#method-map

$mappedProducts = $products->map(function ($product) {
     $mapped = $product;
//not sure what this $productMain varable is
    $mapped['totalQty'] = $productMain->getTypeInstance()->totalQuantity();
return $mapped;
});

This should get you some way towards what you are trying to do.

qTylok's avatar
 $mappedProducts = $product->map(function ($product) {
                $mapped = $product;
                $mapped['totalQty'] = $this->totalQty;
                return $mapped;
            });
            
            $products->push($mappedProducts);

It works, thanks.

drewdan's avatar

@qTylok Glad it worked, if my answer helped, please mark it as the correct answer to help anyone else who stumbles across this page from Google :)

Please or to participate in this conversation.