Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a Paginated variable in Laravel

I am trying to sort a Paginated query result in Laravel. I need to do a sort by descending on the end of everything onto my paginated variable.

Example:

//get some data attach to variable
$variable = DB::table('exampletable')
->where('id',$somevariable)
->select('id','name')
->paginate(10);

//this function will send the variable and attach **total** on each object
$variable = $this->aFunction($variable);

//What I am trying to do, THIS is where I have to sort in the data flow
$variable->sortBy('total', 'desc');

//return data in json format
return response()->json($variable);

I have tried sorting it like said above but I end up with the variable just having names on each segment/object. I have tried and this is the outcome I keep getting:

{
"0":{
      "id": "1",
      "name": "somename",
      "total": "15",
    },
"1":{
      "id": "2",
      "name": "somename2",
      "total": "100",
    },
"2":{
      "id": "3",
      "name": "somename5",
      "total": "26",
    },
}

What I'm trying to achieve is this outcome:

"current_page": 1,
"data": [
  {
      "id": "2",
      "name": "somename2",
      "total": "100",
    },
 {
      "id": "3",
      "name": "somename5",
      "total": "26",
    },
 {
      "id": "1",
      "name": "somename",
      "total": "15",
    },
]
like image 993
IneedToAskQuestions Avatar asked Oct 26 '25 01:10

IneedToAskQuestions


1 Answers

In general

$paginatedUsers is an instance of LengthAwarePaginator documented here: https://laravel.com/api/5.7/Illuminate/Pagination/LengthAwarePaginator.html#method_presenter

We can use setCollection to alter the underlying collection. And items()to extract just the objects at the current page. Then after collecting it we can sort however we want.

$paginatedUsers = User::paginate(3)

$paginatedUsers->setCollection(
    collect(
        collect($paginatedUsers->items())->sortBy('name')
    )->values()
);

full solution (assuming aFunction still returns a Paginator object)

//get some data attach to variable
$variable = DB::table('exampletable')
->where('id',$somevariable)
->select('id','name')
->paginate(10);

//this function will send the variable and attach **total** on each object
$variable = $this->aFunction($variable);

$variable->setCollection(
    collect(
        collect($variable->items())->sortByDesc('total')
    )->values()
);

//return data in json format
return response()->json($variable);
like image 104
ajthinking Avatar answered Oct 27 '25 20:10

ajthinking