To merge two collections in Illuminate/Collections, you can use the concat
method or the merge
method.
Here's an example of using the concat
method:
use Illuminate\Support\Collection;
$collection1 = new Collection([1, 2, 3]);
$collection2 = new Collection([4, 5, 6]);
$mergedCollection = $collection1->concat($collection2);
$mergedCollection->all(); // [1, 2, 3, 4, 5, 6]
And here's an example of using the merge
method:
use Illuminate\Support\Collection;
$collection1 = new Collection(['name' => 'John', 'age' => 30]);
$collection2 = new Collection(['name' => 'Jane', 'email' => '[email protected]']);
$mergedCollection = $collection1->merge($collection2);
$mergedCollection->all(); // ['name' => 'Jane', 'age' => 30, 'email' => '[email protected]']
Note that the concat
method is used to merge the two collections into a new collection, while the merge
method modifies the original collection itself.