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

aavinseth's avatar

filter using laravel collection

Hello,

I have a below array and need to filter the array using laravel collection based on post.type

[
    [
        "name" => "abc",
        "email" => "[email protected]",
        "post" => [
            "id" => 3,
            "type" => 1,
            "title" => "hello"
        ]
    ],
    [
        "name" => "abc",
        "email" => "[email protected]",
        "post" => [
            "id" => 4,
            "type" => 2,
            "title" => "hello"
        ]
    ],
    [
        "name" => "abc",
        "email" => "[email protected]",
        "post" => [
            "id" => 5,
            "type" => 1,
            "title" => "hello"
        ]
    ],
    [
        "name" => "abc",
        "email" => "[email protected]",
        "post" => [
            "id" => 6,
            "type" => 2,
            "title" => "hello"
        ]
    ]
]

based on post type = 2 where condition need a following data

[
    [
        "name" => "abc",
        "email" => "[email protected]",
        "post" => [
            "id" => 4,
            "type" => 2,
            "title" => "hello"
        ]
    ],
    [
        "name" => "abc",
        "email" => "[email protected]",
        "post" => [
            "id" => 6,
            "type" => 2,
            "title" => "hello"
        ]
    ]
]

please let me know how I can achieve this

0 likes
2 replies
vincent15000's avatar

You can do exactly like this.

$array = [...]; // here your array

First you need to convert your array of arrays into a collection of arrays.

$collection = collect($array);

$filtered = $collection->filter(function ($item, $key) {
	return $item['post']['type'] == 2;
});

dd($filtered);
1 like

Please or to participate in this conversation.