How to make associative array from pluck in Laravel

How to make associative array from pluck in Laravel

In this article, we will learn how to make an associative array from pluck in Laravel. To extract certain values from a collection, utilize the Laravel Collections method pluck().

You may frequently want to extract certain data from the collection, in this case the Eloquent collection. The simplest solution is to loop through the collection and extract, but Laravel Collection offers strong helper methods, including the Pluck() method, which makes this task much simpler.

Suppose we have a users table with a lot of information.  We only need the IDs from this table for the users who are currently active. 

Note:  Assume the column name is status, and 1 means active and 0 means not active.  

 
 public function getData()
{
$data = User::where('status', '1')->pluck('id')->toArray();

return $data;
}

Output:

Array [ 
         "1", 
"2", 
"4", 
"5",
]