Laravel collection get columns to array

Viewed 5115

I have collection:

$categories = $post->categories;

I get this:

#items: array:1 [▼
   0 => Category {#999 ▶}
   1 => Category {#999 ▶}
]

I need get from category id.

I try this:

$categories = array_column('id', $post->categories);

But with collections array_column not working. How I can do this?

3 Answers

There are already some good answers.

An alternative is:

$category_ids = $post->categories->pluck('id');

If you want to get any property from a collection, use map higher order message.

example.

$category_ids = $post->categories->map->id;

that's it.

First convert your collection to array. You can use toArray() of eloquent as below.

$categories = $post->categories()->get()->toArray();

And this

$categories = array_column('id', $post->categories);

Should be

$categories = array_column($post->categories, 'id');

Your new code should look like:

$categories = $post->categories()->get()->toArray();

$categories = array_column($categories, 'id');

Ref: array_column

Related