Laravel Collection consists of a bundle of useful functions that in my opinion is compliment with pure PHP’s array functions in many way. Collection as its name may invoke, is a kind of array in the form of object and rather than accessing to the its value by $array[‘key’] as it is in the pure PHP language, we have to use the object style as $collection->key. I feel quite comfortable to work with both. You can check it out here.
So below is a tiny note I want to keep it for later reference when today I worked with some of the call-back functions provided by Laravel Collection, map() and transform() in particular. These functions allow us to “travel” to each item in the collection so then you can change the value in the collection. However, it seems to me, at first, that we cannot pass a variable into these call-back functions. Here is a basic example about what I have written above:
$messages->transform(function ($item, $key) { $item->encrypted = sodium_crypto_box_seal_open(decrypt($item->encrypted), decrypt($privatekeyinput)); return $item; });
What I want to do is to decrypt the encrypted items in the collection named messages. However, I need to use a variable $privatekeyinput that exists in temporary only and it appears that it does not work at all since the call-back function does not find the $privatekeyinput.
I tried to prepend/put another item into the collection it somehow I think I need more time to figure out that way. I also tried to convert the collection into array using toArray() method and I intended to use call-back functions provided by PHP such as array_map() or array_walk() to deal with the array rather than Collection functions given by Laravel. However, as I want to dig a bit deeper into Laravel Collection, I did a search on Google and it turned out that the case could be solved by using a Closure as it is in pure PHP. Then the above code was turned into the following one wherein you can see that a Closure was attached to the call-back function using use($variable).
$messages->transform(function ($item, $key)use($privatekeyinput) { $item->encrypted = sodium_crypto_box_seal_open(decrypt($item->encrypted), decrypt($privatekeyinput)); return $item; });
So now the variable $privatekeyinput has been already defined in the call-back function and it works 🙂