5

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?

1
  • how about $categories = array_column($post->categories,'id');? you just misplaced the arguments Commented Jan 13, 2019 at 12:45

4 Answers 4

14

There are already some good answers.

An alternative is:

$category_ids = $post->categories->pluck('id');
Sign up to request clarification or add additional context in comments.

1 Comment

This answer should be set as solved!
2

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.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.