laraveleloquentlaravel-collection

Laravel simplePaginate() for Grouped Data


I have the following query.

$projects = Project::orderBy('created_at', 'desc');
$data['sorted'] = $projects->groupBy(function ($project) {
    return Carbon::parse($project->created_at)->format('Y-m-d');
})->simplePaginate(5);

When I try to paginate with the simplePaginate() method I get this error.

stripos() expects parameter 1 to be string, object given

How can I paginate grouped data in this case?


Solution

  • The problem was solved. I created a custom paginator via this example: https://stackoverflow.com/a/30014621/6405083

    $page = $request->has('page') ? $request->input('page') : 1; // Use ?page=x if given, otherwise start at 1
            $numPerPage = 15; // Number of results per page
            $count = Project::count(); // Get the total number of entries you'll be paging through
            // Get the actual items
            $projects = Project::orderBy('created_at', 'desc')
                ->take($numPerPage)->offset(($page-1)*$numPerPage)->get()->groupBy(function($project) {
                    return $project->created_at->format('Y-m-d');
                });
            $data['sorted'] = new Paginator($projects, $count, $numPerPage, $page, ['path' => $request->url(), 'query' => $request->query()]);