add new element in laravel collection object

Solution 1:

It looks like you have everything correct according to Laravel docs, but you have a typo

$item->push($product);

Should be

$items->push($product);

push method appends an item to the end of the collection:

I also want to think the actual method you're looking for is put

$items->put('products', $product);

put method sets the given key and value in the collection

Solution 2:

As mentioned above if you wish to add as a new element your queried collection you can use:

    $items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.'  ;'));
    foreach($items as $item){
        $product = DB::select(DB::raw(' select * from product
               where product_id = '. $id.';' ));

        $items->push($product);
        // or 
        // $items->put('products', $product);
    }

but if you wish to add new element to each queried element you need to do like:

    $items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.'  ;'));
    foreach($items as $item){
           $product = DB::select(DB::raw(' select * from product
                 where product_id = '. $id.';' ));
    
          $item->add_whatever_element_you_want = $product;
    }

add_whatever_element_you_want can be whatever you wish that your element is named (like product for example).

Solution 3:

If you want to add item to the beginning of the collection you can use prepend:

$item->prepend($product, 'key');

Solution 4:

If you want to add a product into the array you can use:

$item['product'] = $product;