How to remove the data attribute from a Fractal Transformer result?

I try this code ( via Fractal ) to get the result:

public static function doIt($array, $transformer)
{
    $manager = new Manager();

    $serializer = new \League\Fractal\Serializer\ArraySerializer();
    $manager->setSerializer($serializer);

    if ($array instanceof Collection) {
        $resource = new FractalCollection($array, new $transformer);
    } else {
        $resource = new FractalItem($array, new $transformer);
    }

    return $manager->createData( $resource )->toArray();
}

As you can see, I added

$serializer = new \League\Fractal\Serializer\ArraySerializer();
$manager->setSerializer($serializer);

remove the data attribute from the result array.

array:3 [▼
  "key" => 1
  "title" => "First Level Title"
  "childrens" => array:1 [▼
    "data" => array:16 [▼          ←-------- it need remove!
      0 => array:2 [▼
        "key" => 2
        "title" => "Children Title"
      ]
      1 => array:2 [▶]
      2 => array:2 [▶]
      3 => array:2 [▶]
    ]
  ]
]

Works well, but only for the first level of the array. How to do this to make it work for all nested arrays?

+4
source share
2 answers

I solved this problem. You need to create your own serializer extending the DataArraySerializer. It has three methods and in each of them it is necessary to change the return values:

use League\Fractal\Serializer\DataArraySerializer;

class Serializer extends DataArraySerializer
{
    /**
     * Serialize a collection.
     *
     * @param string $resourceKey
     * @param array  $data
     *
     * @return array
     */
    public function collection($resourceKey, array $data)
    {
        return $data;
    }

    /**
     * Serialize an item.
     *
     * @param string $resourceKey
     * @param array  $data
     *
     * @return array
     */
    public function item($resourceKey, array $data)
    {
        return $data;
    }

    /**
     * Serialize null resource.
     *
     * @return array
     */
    public function null()
    {
        return [];
    }

}
-1
source

You can use unset:

 unset($array['data']);
-2
source

Source: https://habr.com/ru/post/1664993/


All Articles