sulaiman sudirman
sulaiman sudirman

Reputation: 1845

concat collection in Laravel 5.3

I'm trying to concatenate a set collection to another set of collection. I see in Laravel 5.5 it has concat function, but for compatibility reason I have to use until Laravel 5.3 only.

I tried merge function but it is not concatenating but merging instead.

What are other workaround, or how can I update the Laravel Collection without update the whole Laravel package?

Upvotes: 2

Views: 4218

Answers (3)

Yevgeniy Afanasyev
Yevgeniy Afanasyev

Reputation: 41440

A merge function is just what you need.

The documenation says

If the given items's keys are numeric, the values will be appended to the end of the collection:

Which is just what you need.

If you are not sure about items keys, you can always use ->values() function

so the final design would be:

use Illuminate\Support\Collection;
...
$payments = new Collection();
$payments = $payments
            ->merge($payments1->values())
            ->merge($payments2->values());

Upvotes: 0

lagbox
lagbox

Reputation: 50541

You can add functionality to Illuminate\Support\Collection via "macro"s if you want to:

\Illuminate\Support\Collection::macro('concat', function ($source) {
    $result = new static($this);

    foreach ($source as $item) {
        $result->push($item);
    }

    return $result;
});

$new = $someCollection->concat($otherOne);

Copied the method from 5.5.

I have a short blog post about macros in Laravel in general, if it helps:

asklagbox blog - Laravel macros

Laravel 5.5 Docs - Collections - Extending Collections Though this is from 5.5 docs Collection has had this macro functionality for awhile now.

Upvotes: 3

sulaiman sudirman
sulaiman sudirman

Reputation: 1845

Okay nevermind, I'm using code below as workaround,

$first_collection->each(function($element) use (&$second_collection) {

 $second_collection->push($element);

});

Upvotes: 2

Related Questions