vendredi 22 mars 2019

How to map Laravel API resources for Non-Related Models

Hi I'm creating non related model resources. Inventories and Categories. They have child relationship models but they are not connected directly.

Sample Json:

{
  "data": {
    "inventories": [
      {
        "id": 1,
        "user_id": 1,
        "sub_category_id": 6,
        "created_at": "2019-03-08 03:00:00",
        "updated_at": "2019-03-08 03:00:00",
        "deleted_at": null,
        "get_inventory_details": {
          "id": 1,
          "inventory_id": 1,
          "image_path": "Pahiram-Drone1-1.png",
          "name": "Drone i1",
          "description": "Drone i1 The Best Drone yet!",
          "quantity": 10,
          "cost_per_day": 1000,
          "cost_per_hour": 100,
          "status": "0",
          "created_at": "2019-03-08 03:00:00",
          "updated_at": "2019-03-08 03:00:00",
          "deleted_at": null
        }
      }
   ],
 "categories": [
      {
        "id": 1,
        "category_id": 1,
        "parent_id": null,
        "created_at": "2019-03-08 03:00:00",
        "updated_at": "2019-03-08 03:00:00",
        "deleted_at": null,
        "get_sub_category_details": {
          "id": 1,
          "sub_category_id": 1,
          "category_type_id": 1,
          "name": "Drone DJI 1",
          "description": "Drone DJI 1",
          "created_at": "2019-03-08 03:34:23",
          "updated_at": "2019-03-08 03:34:23",
          "deleted_at": null
        }
      }
]

This is my sample data

It works with:

    public function toArray($request)
    {
        return parent::toArray($request);
    }

But not:

     public function toArray($request)
     {
         return [
             'inventory_ids' => $this->inventories->id,
             'category_ids' => $this->categories->id
         ];
     }

My expected result is to be able to map my Json response.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire