Latest

Thursday, July 6, 2017

Getting error while using GroupBy and Pagination in Eloquent

Asked by: joao.sauer


I'm trying to use eloquent to get me a grouped by response and at the same time give me a Pagination response (The one that gives me the link to the second page). I'm trying to do this:

App\Eating::Where('student_id', 2)->orderBy('created_at', 'DESC')->groupBy(function ($row) {
     return Carbon\Carbon::parse($row->created_at)->format('Y-m-d');
})->paginate(25);

But, I'm getting this error when running it in the Tinker:

PHP warning:  strtolower() expects parameter 1 to be string, object given in D:\Folder\vendor\laravel\framework\src\Illuminate\Database\Grammar.php on line 58

without the groupBy, I'm getting the correct result:

>>> App\Eating::Where('student_id', 2)->orderBy('created_at', 'DESC')->paginate(25)->toArray();
=> [
     "total" => 1,
     "per_page" => 25,
     "current_page" => 1,
     "last_page" => 1,
     "next_page_url" => null,
     "prev_page_url" => null,
     "from" => 1,
     "to" => 3,
     "data" => [
       [
         "id" => 5,
         "status" => "Comeu Bem",
         "created_at" => "2017-07-05 13:55:25",
         "updated_at" => "2017-07-05 13:55:25",
       ],
     ],
   ]

BUT, when I remove the pagination, I do get the error but only because I added the get():

>>>  App\Eating::Where('student_id', 2)->orderBy('created_at', 'DESC')->groupBy(function ($row) {
...                          return Carbon\Carbon::parse($row->created_at)->format('Y-m-d');
...                      })->get();
PHP warning:  strtolower() expects parameter 1 to be string, object given in D:\Joao\git\F1Softwares\Code\Server\F1Softwares\vendor\laravel\framework\src\Illuminate\Database\Grammar.php on line 58
>>>
>>>  
>>>  App\Eating::Where('student_id', 2)->orderBy('created_at', 'DESC')->groupBy(function ($row) {
...                          return Carbon\Carbon::parse($row->created_at)->format('Y-m-d');
...                      });
=> Illuminate\Database\Eloquent\Builder {#855}

Any idea what I could be doing wrong? I do need to have the orderBy AND the pagination, to make it easier for the app to show the results(It is a RestFul call).

Thanks, João



Source

No comments:

Post a Comment

Adbox