0

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?

user137
  • 629
  • 1
  • 8
  • 20

4 Answers4

2

The created_at attribute is already casted as a Carbon Object (by default in laravel models). that's why you are getting that error. Try this:

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

this answer is just for the error you're getting. now if you want help with the QueryBuilder, can you provide an example of the results you're expecting to have and an example of the database structure ?

N69S
  • 16,110
  • 3
  • 22
  • 36
0

The pagination methods should be called on queries instead of collection.

You could try:

$projects = Project::orderBy('created_at', 'desc');
$data['sorted'] = $projects->groupBy('created_at');
D Malan
  • 10,272
  • 3
  • 25
  • 50
  • I can't group by raw **created_at field**... I need to format it to 'Y-m-d' before... Look at my first post. I've update the issue description – user137 Feb 01 '19 at 14:35
0

The problem was solved. I was create 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()]);
user137
  • 629
  • 1
  • 8
  • 20
0

simplePaginate Method is exist in the path below:

Illuminate\Database\Eloquent\Builder.php::simplePaginate()
David Buck
  • 3,752
  • 35
  • 31
  • 35
Baseer Ebadi
  • 113
  • 3