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?
pluck('user_id')->values()
– Kamlesh Paulpluck('user_id')->values()
on my collection and then add ontoArray()
it returns an array but with numerical keys.array:2 [▼ 0 => 12345 1 => 12346 ]
but I want the0,1
to beuser_id
– PA-GW