0
votes

I am working with Laravel and currently I have an eloquent Collection being returned with 3 arrays within the collection. Within each array are nested Model collections.

The structure is like so:

Illuminate\Database\Eloquent\Collection {#1905 ▼
  #items: array:3 [▼
    0 => app\Models\User {#1804 ▶}
    1 => app\Models\User {#1805 ▶}
    2 => app\Models\User {#1806 ▶}
  ]
}

Each user is like so when expanded

#attributes: array:3 [▼
        "user_id" => 12345
        "first_name" => "John"
        "last_name" => "Doe"]

What I want to have returned is an array with just the user_id => 12345 for all the users.

I tried the traditional foreach but the index keep returning as 0 => 12345 instead of user_id as my key. I also tried pluck() to pull the user_id but I got the same result of a numeric key.

Is there an efficient way to achieve this using eloquent?

1
use pluck('user_id')->values()Kamlesh Paul
@KamleshPaul if I use pluck('user_id')->values() on my collection and then add on toArray() it returns an array but with numerical keys. array:2 [▼ 0 => 12345 1 => 12346 ] but I want the 0,1 to be user_idPA-GW

1 Answers

1
votes

Pluck would not work since user_id is the value from the collection you are extracting.

Why not just do a select with only the fields you want...Instead of removing things from collection you don't need?

For example this would return an array of arrays with a key id and value being that id.

User::select('id')->get()->toArray();
 [
     [
       "id" => 1,
     ],
     [
       "id" => 2,
     ],
]

But to do what you want given the data you have you could use map and return only the key-value data you need. Here is a short example:

$collection = [
  [
    "user_id" => 12345,
    "first_name" => "John",
    "last_name" => "Doe",
  ],
  [
    "user_id" => 12346,
    "first_name" => "John 2",
    "last_name" => "Doe",
  ],
  [
    "user_id" => 12347,
    "first_name" => "John 3",
    "last_name" => "Doe",
  ],
];

collect($collection)->map(function ($user) {
  return [
    "user_id" => $user["user_id"],
  ];
});

Keep in mind this way from an start array so in your case I am assuming you be doing like:

User::get()->map(function ($user) {
  return [
    'user_id' => $user->user_id,
  ];
});