Question: Merge fields laravel collections

Question

Merge fields laravel collections

Answers 3
Added at 2017-01-01 13:01
Tags
Question

I have two Laravel collections. Mi first collection called $custom_product:

Collection {#313 ▼
  #items: array:1 [▼
    0 => array:1 [▼
      "custom_description" => "insert description here"
    ]
  ]
}

And I have my other collection called $api_product:

Collection {#311 ▼
  #items: array:29 [▼
    "article_id" => 5570
    "active" => null
    "name" => "CORBATA POLIESTER"
    "detail" => "- Pesa: 43 gr."
    "constructor_name" => "gift"
    "stock_available" => true
    "stock" => null
    "prices" => array:6 [▶]
    "price_pvp" => 29.0
    "size" => "1410X100"
  ]
}

I want this result. The same collection but with the field custom_description added:

Collection {#311 ▼
  #items: array:29 [▼
    "article_id" => 5570
    "active" => null
    "custom_description" => "insert description here"//add this field
    "name" => "CORBATA POLIESTER"
    "detail" => "- Pesa: 43 gr."
    "constructor_name" => "gift"
    "stock_available" => true
    "stock" => null
    "prices" => array:6 [▶]
    "price_pvp" => 29.0
    "size" => "1410X100"
  ]
}
Answers
nr: #1 dodano: 2017-01-01 13:01

You may use put method of laravel collection.

$collection = collect(['product_id' => 1, 'name' => 'Desk']);

$collection->put('price', 100);

$collection->all();

// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]
nr: #2 dodano: 2017-01-01 13:01

You can itarete over collections and add fields manually as with simple array:

for ($i = 0; $i < count($secondCollection); $i++) {
    // Add field to an item.
    $secondCollection[$i]['custom_description'] = $firstCollection[$i]['custom_description'];
}

This code will give an idea. Actual code is really depends on collections structure.

nr: #3 dodano: 2017-01-01 16:01

In the case that you were doing this per individual record using the examples given, I think it would be:

$api_product->put($custom_product->toArray()[0]);

If you wanted to combine multiple records you could use the map() method

$api_products_collection->map(function($key,$item) {
    //combine the record
    return $item;
});
Source Show
◀ Wstecz