rohitkhatri
3 years ago
2972
11
Laravel

How to add a new element to every item of collection?

Posted 3 years ago by rohitkhatri

I have a multidimensional array collection and I want to add a particular element of every sub array.

Code:

$posts = collect([
    ['id'=>1,'title'=>'Post one'],
    ['id'=>2,'title'=>'Post two'],
    ['id'=>3,'title'=>'Post three'],
    ['id'=>4,'title'=>'Post four'],
]);

Now I want to add 'url' attribute in every sub array, so how do I do that in laravel way? Is there any one line function in collection class? or any better way of doing this without looping?

Please sign in or create an account to participate in this conversation.