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.

2

2 Answers 2

2

You can use pluck

$milestoneIds = $collection->pluck('pivot.milestone_id')->toArray();
Sign up to request clarification or add additional context in comments.

1 Comment

This worked! Thank you! I used implode() method to get only the values.
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

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.