Search code examples
phplaravelpaginationeloquentlaravel-collection

Paginate timeline groupBy date with laravel


I'm building a timeline for patients exams, they look like this:

timeline patients exams

When I click in a patients will be showed all exams which he has done, the method used is:

return view('papeis.paciente.historico', [
        'vinculos' => Vinculo::where('paciente_id',$id)->get()->sortByDesc('admissao')
            ->groupBy(function ($item, $key) {
                return $item->admissao->format('d/m/Y');
            }),
        'paciente' => Paciente::findOrFail($id),
    ]);

The patients exams ("Vinculo") are groupBy the date "admissao", to show the date and the exams who he did at that day. I can't use paginate a collection, so I don't have idea how to paginate a groupBy collection.


Solution

  • I don't think Laravel natively supports that, but you can build it yourself:

    $admissaoes = Vinculo::where('paciente_id', $id)->distinct()
        ->select('admissao')->orderByDesc('admissao')->get();
    $page = Paginator::resolveCurrentPage() ?: 1;
    $perPage = 5;
    $pageAdmissaoes = $admissaoes->forPage($page, $perPage);
    $paginator = new LengthAwarePaginator($pageAdmissaoes, $admissaoes->count(), $perPage, $page);
    $vinculos = Vinculo::where('paciente_id', $id)
        ->whereIn('admissao', $pageAdmissaoes->pluck('admissao'))
        ->orderByDesc('admissao')->get();