How to add an php array to laravel collection. how to merge two collection or collection to array. laravel collection union method. laravel merge vs union method.
Laravel collection merge array
The merge method add given array to the laravel collection. In merge method have two type of conditions first when keys are string type In this case if original collection and given array have same string keys new array key value replace old collection value.
Second case when keys are numeric and both have same numeric keys merge method append all values in collection no value replace.
$collection = collect(['name' => 'anmol', 'email' => anmol@gmail.com]); $merged = $collection->merge(['name' => 'anmol sharma', 'age' => 24]); dd($merged); // ['name' => 'anmol sharma', 'name' => 'anmol sharma', 'age' => 24]
$collection = collect([1 => 'hindi', 2 => 'english']); $merged = $collection->merge([1 => 'french', 2 => 'urdu']); dd($merged); // ['hindi', 'english', 'french', 'urdu']
Laravel collection union method
The laravel collection union method also uses for merging two collections or arrays into the collection. when we combined an array with the collection and the array has same key then original collection not change and the new array value is removed.
collection = collect([1 => ['a'], 2 => ['b']]); $union = $collection->union([3 => ['c'], 1 => ['d']]); dd($union); // [1 => ['a'], 2 => ['b'], 3 => ['c']]
Laravel collection union vs merge method
Laravel collection union and merge both methods use for adding array and collection but in case of same key merge replace original value with new and merge is opposite it prefer keeping original value.