phplaravellaravel-7

Paginate for a collection, Laravel


I try to add some new values to each user from foreach, but because I use get, now I can't use paginate on response, but I also need to add that values to each user. Any ideas?

public function statistics()
    {
        $users = User::select(['id', 'name'])->get();
        foreach ($users as $key => $user) {
            $history = AnswerHistory::where('user_id', '=', $user->id)->get();
            $user->total_votes = count($history);
            $user->total_time = gmdate("H:i:s", ($history->sum('answer_time')));
        }

        return response()->json($users);
    }

Solution

  • According to your post, User has many AnswerHistory. You can build relationship between them.

    So getting the total_votes and total_time by withCount:

    $users = User::withCount('answerHistories AS total_votes')
         ->withCount(['answerHistories AS total_time' => function($query) {
               $query->select(DB::raw("SUM(answer_time)"));
         }])->paginate(10);
    

    And you can get the pagination datas by getCollection, and change the datas inside:

    $users->getCollection()->transform(function ($data) {
        $data->total_time = gmdate('H:i:s', $data->total_time);
        return $data;
    });