How to merge Collection in Laravel?

To merge two collection col1 and col2 we use merge() method of collection

$collection = collect();
$collection->merge(['col1' => $col1, 'col2' => $col2 ]);

OR

We can just pass those collection while declaring the collection

$collection = collect([
        'col1' => $col1,
        'col2' => $col2
    ]);

Some Example case

Sometimes we need to get different collection from same Database Table depending on a particular column but we don’t know the no of collections

Then we merge those collection together in a parent collection.

So for e.g. we need users by different city

// this data source can be a static array 
// or a dynamic collection
$states = [
            'Delhi', 
            'Tamil Nadu', 
            'Uttar Pradesh', 
            'Haryana', 'Maharashtra', 
            'Punjab', 
            'Rajasthan', 
            'Bihar'
        ];

// collection helper used to define new Collection
$stateUser = collect();

foreach ($states as $state)
{
    // getting user by a particular city with status 1
    $data = DB::table('user')
        ->select('user.*')
        ->where("user.city", $state)
        ->where('user.status', 1)
        ->get();

    // merging the collection by the key name of state 
    // if collection is not empty
    if (!empty($data[0])) 
    $stateUser = $stateUser->merge([$state => $data]);
}

Leave a Reply

Your email address will not be published. Required fields are marked *