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?
CodePudding user response:
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.
CodePudding user response:
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');
CodePudding user response:
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;
}