dimanche 25 novembre 2018

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",
    },
]



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire