How can I get data by grouping user_id
for a foreach loop in a controller's function in Laravel. For example, user_id = 2
, 5 rows available, user_id = 1
, 10 rows available. Then show 2 arrays.
$lists = lists::wherestatus(1)->groupby('user_id')->get();
foreach($lists as $list){
$list = functionHere;
}
What function can I create for this on the controller for grouping?
CodePudding user response:
I need more information, but based on what you shared, you should be able to do this (removing the foreach
):
$lists = Lists::whereStatus(1)->get()->groupBy('user_id');
The difference is that if you use groupBy
before get
, you are grouping your query by user_id
, so instead of getting 5 rows for user_id = 2
and 10 for user_id = 1
, you are going to get 2 rows and just the latest data, so you need to use Collection's groupBy
.
What you want to do is group all the information by user_id
but have each row, a schema like this:
[
'1' => [ // user_id
['user_id' => '1', 'column1' => 'random value'],
['user_id' => '1', 'column1' => 'other value'],
// 8 remaining rows
],
'2' => [ // user_id
['user_id' => '2', 'column1' => 'other nice value'],
// 4 remaining rows
],
]
CodePudding user response:
you should first in List model set:
public function scopeStatus(){
return $this->where('status','1'); }
and in your controller:
$products = List::status()->groupby('user_id')->get();