How to combine laravel collections

Mattsuyolo
2 min readMay 9, 2021

Scenario:

Tommy’s boss asked him to produce a report about both Asia and Euro 10 best seller .‘’That ‘s a piece of cake ”,said naive Tommy.

//two model has exactly same column$asia_best_seller = App/AsiaSeller::select("name", "sales_volume", "birth_day", "on_board_day")
->orderBy("sales_volume", "desc")
->take(10)
->get();
$euro_best_seller = App/AsiaSeller::select("name", "sales_volume", "birth_day", "on_board_day")
->orderBy("sales_volume", "desc")
->take(10)
->get();

Tommy need to sort the sales volume from more to less and turn birthday into age.

//wrong example$asia_best_seller->merge($euro_best_seller);//you will get only one collect !!

let’s see what collection method merge described in document below

The merge method merges the given array or collection with the original collection. If a string key in the given items matches a string key in the original collection, the given items's value will overwrite the value in the original collection:

$collection = collect(['product_id' => 1, 'price' => 100]);$merged = $collection->merge(['price' => 200, 'discount' => false]);$merged->all();// ['product_id' => 1, 'price' => 200, 'discount' => false]

Answer

Just put two collection into one array and use flatten to get rid of the key.

$tempCollection = collect([$asia_best_seller, $euro_best_seller]);//combined collection $Collection = $tempCollection->flatten(1);
->sortBy("sales_volume","desc");

Detailed as below

$asia_best_seller
$euro_best_seller
$tempCollection = collect([$asia_best_seller, $euro_best_seller]);
$Collection = $tempCollection->flatten(1);
->sortBy("sales_volume","desc");

PS:

If two table are small , use union to combine two tables will be the appropriate choice. However when rows lager than ten thousands , select union table will be really slow.

--

--

Mattsuyolo

The greats never sacrifice the important for the urgent