Skip to content
Advertisement

Laravel 5.4 Combining two collections

So I Have two collections, sales and costs.

Now I need them to combine into one collection for my foreach condition (I’m not sure if I can use two collections in one foreach)

RAW Queries:

JavaScript

Here’s my query for these two collections:

JavaScript

Things I’ve tried testing: Converting the collections into array and tried merging them but I seem to have problems.

I reverted it because I don’t know if it’s the best way or not. Please let me know what’s the best way.

UPDATE: Here’s the output for those two queries, hope it helps:

Sales

JavaScript

Costs

JavaScript

What I tried: (It says it cannot find totalCost)

JavaScript

**SOLVED: ** I used collection merge (didn’t knew there was such a thing)

The syntax I used is, $result = $sales->merge($costs).

Here’s the result:

JavaScript

Answered by: Sagar Gautam

Advertisement

Answer

Use collection merge() function like

JavaScript

You can see docs https://laravel.com/docs/5.4/collections#method-merge

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement