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

tapas's avatar
Level 15

Need help with formatting laravel collection

Thanks in advance! I have the following collection.

$collection = collect([
    [
        'id' => 1,
        'filter' => 'brand',
        'value' => 'apple'
    ],
    [
        'id' => 2,
        'filter' => 'color',
        'value' => 'red'
    ],
    [
        'id' => 3,
        'filter' => 'color',
        'value' => 'blue'
    ],
    [
        'id' => 3,
        'filter' => 'storage',
        'value' => '8GB'
    ]
]);

I need it exactly like this:

[
    "brand" => ["apple"],
    "color" => ["red", "blue"],
    "storage" => ["8GB"]
]

Or I need to transform it like this:

$transformed = collect([
    [
        'filter' => 'brand',
        'value' => ['apple']
    ],
    [
        'filter' => 'color',
        'value' => ['red', 'blue']
    ],
    [
        'filter' => 'storage',
        'value' => ['8GB']
    ]
]);

How can I do this?

0 likes
2 replies

Please or to participate in this conversation.