0

Is there way i can rename the data key in laravel collection results? At the moment this

DB::table('contracts AS C')->paginate(1)

returns

  {
  "current_page": 1,
    "data": [
        {
            "id": 191,
            "buyer": "John",
            "provider": "Jane"
        }
    ],
    "from": 1,
    "last_page": 1,
    "next_page_url": "",
    "path": "",
    "per_page": 1,
    "prev_page_url": null,
    "to": 1,
    "total": 1
}

What i would like is this

  {
  "current_page": 1,
    "parties": [
        {
            "id": 191,
            "buyer": "John",
            "provider": "Jane"
        }
    ],
    "from": 1,
    "last_page": 1,
    "next_page_url": "",
    "path": "",
    "per_page": 1,
    "prev_page_url": null,
    "to": 1,
    "total": 1
}

The challenge here changing the data key to parties

Cengkuru Michael
  • 4,590
  • 1
  • 33
  • 33

4 Answers4

7

You could use the keyBy() method of collection.

$unfiltered = DB::table('contracts AS C')->paginate(1);

$filtered = $unfiltered->keyBy(function ($value, $key) {
     if ($key == 'data') {
         return 'parties';
     } else {
         return $key;
     }
});

return $filtered;
linktoahref
  • 7,812
  • 3
  • 29
  • 51
1

You could just convert the collection to array and manipulate it:

$result = DB::table('contracts AS C')->paginate(1)->toArray();
$data = $result['data'];
unset($result['data']);
$result['parties'] = $data;

return $result;

This does not require any extra loops either.

Paranoid Android
  • 4,672
  • 11
  • 54
  • 73
0

The data key is only set when the Paginator object toArray() is called. Before that it's a Collection with the key items.

Quick and dirty solution would be to call toArray() on the Paginator object and change the key name of the array before the json_encode().


Another solution would be to extend the Builder class, much like it's done here, overwrite the paginate() method and Paginator's toArray() method.

Robert
  • 5,703
  • 2
  • 31
  • 32
0

you can return data with below code :

$coins = CoinResource::collection(Cryptocurrency::all());
return ['your_custom_name' => $coins];