Gabriel I.
Gabriel I.

Reputation: 123

Laravel - Collection merge() returning a single row

I have a problem with Model Collections (Eloquent).

I have two Collection of the Model ActivationDetail and I need to merge them into a single collection, the collection have the same structure so it wouldn't be hard to merge them right?

Well, searched in the internet and the API itself I've came across the merge() method which allows me to combine two collections into one. Like found here, here, and here.

However, this method is returning me a single row. (sizeof($detail) is returning 1) Although in the correct format, I don't know what I'm missing here.

What I am doing wrong?

//first collection
$detail = ActivationDetail::[redacted]->get();

// second collection, the query is of the same structure 
// as the previous one, but it's edited to allow the selection 
// of null fields (which can't be possible in the previous 
// due how Inner Joins work)
$detailB = ActivationDetail::[redacted]->get();

$detail = $detail->merge($detailB);

//this returns "1"
dd(sizeof($detail));

Upvotes: 1

Views: 1926

Answers (1)

Jerodev
Jerodev

Reputation: 33196

If you are running two queries that have the same columns in the result set, you might want to take a look at unions. This will join the two queries in one query that merges the results for you.

$query1 = ActivationDetail::[redacted];
$detail = ActivationDetail::[redacted]->union($query1)->get();

Upvotes: 1

Related Questions