Dumitru
Dumitru

Reputation: 2173

Laravel collection get columns to array

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?

Upvotes: 5

Views: 9764

Answers (4)

userSixtyNine
userSixtyNine

Reputation: 1

I know that was asked 11 years ago but having same question and here the solution that works in laravel 10.x:

$categories->groupBy('category_id')

It will returns:

[
  112 => [Category],
  420 => [Category],
  ...
  n => [Category]
]

Source: https://laravel.com/docs/10.x/collections#method-groupby

Upvotes: 0

Mozammil
Mozammil

Reputation: 8750

There are already some good answers.

An alternative is:

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

Upvotes: 14

Tharaka Dilshan
Tharaka Dilshan

Reputation: 4499

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.

Upvotes: 2

Iftikhar uddin
Iftikhar uddin

Reputation: 3182

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

Upvotes: 1

Related Questions