PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, March 9, 2022

[FIXED] Adding attributes to laravel collection

 March 09, 2022     collections, laravel, php     No comments   

Issue

i have to put some attributes to my laravel collections.

My laravel collection original attributes :

array:2 [▼
    0 => array:20 [▼
        "curr" => "IDR"
        "price" => 5500000.0
        "rate" => 14325.803
        "qty" => 2
    ]
    1 => array:20 [▼
        "curr" => "IDR"
        "price" => 1500000.0
        "rate" => 14325.803
        "qty" => 1
    ]
]

i want to add "amount" attribute which the result of multiplying "price" x "qty" like so :

array:2 [▼
    0 => array:20 [▼
        "curr" => "IDR"
        "price" => 5500000.0
        "rate" => 14325.803
        "qty" => 2
        "amount" => 11000000.0
    ]
    1 => array:20 [▼
        "curr" => "IDR"
        "price" => 1500000.0
        "rate" => 14325.803
        "qty" => 1
        "amount" => 1500000.0
    ]
]

i tried to do it by put() method of laravel collection, but it seems the each() method will remove the collection instance, so i can't use the put() method :

$collection->each(function($item) {
    $item->put('amount', $item->price * $item->qty);
});

What's the solution of this ?


Solution

You can't use ->put in an ->each loop for this case, because ->each does not loop the items by reference. So all modifications to the item are lost after the loop.

You can map the array to return your actual $item merged with the extra key amount. The correct method to use is ->map.

$collection = $collection->map(function($item) {
    return array_merge($item, [
        'amount' => $item->price * $item->qty;
    ]);
});

https://laravel.com/docs/9.x/collections#method-map



Answered By - julianstark999
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing