skip to Main Content

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

Answers


  1. 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

    Login or Signup to reply.
  2. You can use pluck

    $milestoneIds = $collection->pluck('pivot.milestone_id')->toArray();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search