2

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?

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@sulaiman updated macro example to be the method you need from 5.5
2

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

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

 $second_collection->push($element);

});

Comments

0

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.