radiate-framework / framework

A WordPress plugin and theme framework
https://radiate-framework.github.io/
MIT License
4 stars 0 forks source link

JsonResource toArray return type is restrictive #54

Closed BenRutlandWeb closed 3 years ago

BenRutlandWeb commented 3 years ago

Describe the bug Nested JsonResource's collection should be able to return any JSONable type, not just an array.

To Reproduce Steps to reproduce the behavior:

  1. Make a new resource with a nested resource
  2. return a string. E.g.
    
    // recipe resource
    public function toArray()
    {
    return [
        'ingredients' => IngredientResource::collection($this->ingredients),
    ];
    }

// ingredient resource public function toArray() { return $this->name; }

3. This will cast the name to an array so the result is:
```json
{
  "ingredients": [
    ["eggs"],
    ["milk"]
  ]
}

Expected behavior The toArray method to return any JSONable type, string, int, bool, object, array E.g.

{
  "ingredients": [
    "eggs",
    "milk"
  ]
}

Additional context The toArray method name implies the return will be an array but this seems restrictive in instances where the collection should return a simple array of strings.

BenRutlandWeb commented 3 years ago

toArray should always return an array. To achieve the above, use an array instead of a collected resource:

// recipe resource
public function toArray()
{
    return [
        'ingredients' => $this->ingredients->pluck('name'), // or whatever mapping is required
    ];
}