1

I get a Laravel collection from a Eloquent query and I converted into an array using toArray() method. The sample output is mentioned below.

Array ( [0] => Array ( [id] => 1 [details] => routes [level] => beginner [created_at] => 2022-11-16T11:09:48.000000Z [updated_at] => 2022-11-09T11:09:48.000000Z [pivot] => Array ( [user_id] => 1 [milestone_id] => 1 ) ) [1] => Array ( [id] => 2 [details] => router 2 [level] => beginner [created_at] => 2022-11-09T11:09:48.000000Z [updated_at] => 2022-11-18T11:09:48.000000Z [pivot] => Array ( [user_id] => 1 [milestone_id] => 2 ) ) [2] => Array ( [id] => 3 [details] => route [level] => route 3 [created_at] => 2022-11-15T09:05:46.000000Z [updated_at] => 2022-11-17T09:05:46.000000Z [pivot] => Array ( [user_id] => 1 [milestone_id] => 3 ) ) ) 1

I only need the values of milestone_ids from pivot index. As an example like this [1,2,3]

I tried different PHP methods and notations to access these values but couldn't succeed.

pasindu
  • 529
  • 1
  • 4
  • 16
  • 4
    What did you try and what specifically went wrong? – showdev Nov 10 '22 at 03:51
  • Related: [Laravel pluck an array from nested relationship](https://stackoverflow.com/q/50249341/2943403) and [Laravel pluck fields from relations](https://stackoverflow.com/q/40635146/2943403) and [How to get only nested data in Laravel collection](https://stackoverflow.com/q/69844985/2943403) – mickmackusa Nov 10 '22 at 05:49

2 Answers2

2

You can use pluck

$milestoneIds = $collection->pluck('pivot.milestone_id')->toArray();
keyboardSmasher
  • 2,661
  • 18
  • 20
0

You could foreach or array_map through the array

$milestone_ids = array_map(function($data){
    return $data['pivot']['milestone_id'];
}, $pivot);

The other way would be to use a loop to go through each data set in the array and get the value you are looking for and drop it in another array.

https://www.mycompiler.io/view/7jWliNt2Vo0

dvnc0
  • 19
  • 3