'Laravel foreach to retrive user IDs
In my laravel project i has model Promo, where located only user_id column.
I have 2 records in this Model.
I need to retrive all user_id's from Promo model.
First i take all user_id's from Model:
$userList = Promo::get();
dd say me, that i has 2 records:
This true result, than i try to make foreach:
foreach ($userList as $userIds) {
$userIds = $userIds->user_id;
}
And if i use var_dump or dd, it's always show to me 1 user_id, but i has 2 user_id in table.
Where can be mistake?
Solution 1:[1]
You are replacing the value of $userIds each time the loop count and the final value is the last value of the $userList.
You can do it in 2 different ways:
with the loop:
$userList = Promo::get();
$userIds = [];
foreach ($userList as $user) {
$userIds[] = $user->user_id;
}
or with the Laravel collection pluck() (recommended):
$userIds = Promo::pluck('user_id');
Solution 2:[2]
You're overwriting $userIds each time. There's an easier way to get just the user Ids
$userIds = $userList->pluck('user_id')->all();
This will return an array of user_ids from your userList collection.
Solution 3:[3]
In your code you're assigning user id to $userIds variable. It always returns one value. Try this,
$userIdsarray =[] ;
foreach ($userList as $userIds) {
$userIdsarray[] = $userIds->user_id;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | aynber |
| Solution 3 |

