phplaravellaravel-5

add new element in laravel collection object


I want to add new element in $items array, I don't want to use joins for certain reasons.

$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->push($product);
}

What should I do?


Solution

  • 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