Reputation: 2173
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
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
Reputation: 8750
There are already some good answers.
An alternative is:
$category_ids = $post->categories->pluck('id');
Upvotes: 14
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
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