Shahneel Ahmed
Shahneel Ahmed

Reputation: 173

laravel collect function is undefined

i am getting data from database which in need to group so i am converting database result set in to array and then passing it to laravel collect helper but i gives me error

Call to undefined function collect()

Code

  $user_profile=collect(UserProfileItem::where('type', "age_group")->get()->toArray())->groupBy("age_group");

please help me about what i am doing wrong i want to use laravel collections method groupby to group my database result array by "age_group"

like below data group by account_id

 [
        'account-x10' => [
            ['account_id' => 'account-x10', 'product' => 'Chair'],
            ['account_id' => 'account-x10', 'product' => 'Bookcase'],
        ],
        'account-x11' => [
            ['account_id' => 'account-x11', 'product' => 'Desk'],
        ],
    ]

Upvotes: 1

Views: 1824

Answers (3)

Shahneel Ahmed
Shahneel Ahmed

Reputation: 173

i think for previous version of laravel creating your own group is the only solution

   public function getGroupedUser($group="age_group"){

        $users = $this->users->keyBy('id')->toArray();
        $user_profile=UserProfileItem::where('type', "age_group")->get()->groupBy("age_group");
        foreach ($user_profile as $row){
            $urow[$row['data']][]=$row;
        }
    echo "<pre>";
        print_r($user_profile);die;
    }

Upvotes: 0

Pooja Yengandul
Pooja Yengandul

Reputation: 41

You dont need to add collect function as you are already getting a collection. So you need to do it as :

$user_profile = UserProfileItem::where('type', "age_group")->get()->groupBy("age_group");

Upvotes: 2

Chamara Abeysekara
Chamara Abeysekara

Reputation: 1322

you need to first get the groups and loop through them and add data in those to the collection

$groups = UserProfileItem::groupBy("age_group")->get();
$collection = collect();

foreach($groups as $group){
  $data = UserProfileItem::where('type', $group->type)->get();

  $collection->put($group->type , $data);
}

return $collection;

Upvotes: 1

Related Questions