Skip to content

Latest commit

 

History

History
78 lines (58 loc) · 1.76 KB

conversion.md

File metadata and controls

78 lines (58 loc) · 1.76 KB

REST API Response Builder for Laravel

Data conversion

« Documentation table of contents


On-the-fly data conversion

ResponseBuilder can save you some work by automatically converting objects into array representation. For example, having ResponseBuilder configured to auto-convet objects of Eloquent's Model class and passing object of that class either directly using withData() or as part of bigger structurre) will have it converted to JSON format automatically.

The following classes are supported out of the box:

  • \Illuminate\Database\Eloquent\Model
  • \Illuminate\Support\Collection
  • \Illuminate\Database\Eloquent\Collection
  • \Illuminate\Http\Resources\Json\JsonResource
  • \Illuminate\Pagination\LengthAwarePaginator
  • \Illuminate\Pagination\Paginator

Examples

Passing single model, like this:

$flight = App\Flight::where(...)->first();
return RB::success($flight);

will return:

{
   "item": {
      "airline": "lot",
      "flight_number": "lo123",
      ...
   }
}

If you have more data, then pass the Collection:

$flights = App\Flight::where(...)->get();
return RB::success($flights);

which would return array of your objects:

{
   "items": [
      {
         "airline": "lot",
         "flight_number": "lo123",
         ...
      },{
         "airline": "american",
         "flight_number": "am456",
         ...
      }
   ]
}

Configuration

The whole functionality is configurable using converter array. See Converter configuration for more information.