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",
},
]
$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()
);
//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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With