Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

chrislentz's avatar

Does anyone know of a easy way to manipulate a collection item?

I am having to use the L5 query builder to pull some data with some advanced relationships and some advanced joins.

Because I am using the query builder, my created_at timestamp is not being returned as a Carbon instance.

I was curious is anyone knows and easy way to manipulate a collections items? I know I can loop through them and make my adjustment. I was just curious if Laravel has a shorthand method to accomplish this?

I pretty much just want to convert "created_at" for all my collection items into a Carbon instance, so I am not messing with the structure or naming conventions of the collection.

0 likes
3 replies
luddinus's avatar
Level 6

Try this

$collection->map(function($item) {
    $item->attributes['created_at'] = Carbon::whatever($item->created_at); // I don't remember the method

    return $item;
});
chrislentz's avatar

Thanks @luddinus! That is exactly what I was looking for.

I made one minor tweaks.

$collection->map(function($item) {
    $item->created_at = Carbon::parse($item->created_at);

    return $item;
});

Please or to participate in this conversation.