Table of contents
 
                            Laravel collection merge method able us to merge the given array or collection to the original collection. This will help us if we have a functionality we want to connect to the existing collection from the updated collection with additional keys.
Â
Â
Example Laravel Collection #1:
public function index()
{
    $collection = collect(['user_id' => 1, 'age' => 25]);
	$merged = $collection->merge(['gender' => 'male']);
	$merged->all();
 
    //['user_id' => 1, 'age' => 25, 'gender' => 'male']
}
If you want to use the Laravel collection merge() method to update the key value of the existing collection here is the example below.
Â
Example Laravel Collection #2:
public function index()
{
	$collection = collect(['user_id' => 1, 'age' => 25]);
	$merged = $collection->merge(['age' => 30]);
	$merged->all();
	// ['user_id' => 1, 'age' => 30]
}Â
As you can see the age value has been updated to 30 from 25.
Â
Â
Example Laravel Collection #3:
For the items that the keys are numeric, the values will only be appended to the end of the collection.
public function index()
{
	$collection = collect(['red', 'blue', 'green']);
	$merged = $collection->merge(['yellow', 'orange']);
	$merged->all();
	// ['red', 'blue', 'green', 'yellow', 'orange']
}Â
That's pretty much it. I hope it helps :)
Read next

 
                        