Search code examples
phptransformer-modelthephpleague-fractal

Parsing includes for nested tranformers


I'm trying to figure out how I can parse includes for nested transformers, given the scenario below:

I have a controller which sets my ArraySerializer, parses includes for the OrderTransformer and then creates the data:

$data = (new Manager())
    ->setSerializer(new ArraySerializer())
    ->parseIncludes('dispatches')
    ->createData(new Collection($orders, new OrderTransformer()));

Inside my order transformer I have the include dispatches which I'm parsing from the above:

class OrderTransformer
{
    protected $availableIncludes = [
        'dispatches',
    ];

    public function transform($order)
    {
        return [];
    }

    public function includeDispatches($order)
    {
        return $this->collection($order->getDispatches(), new DispatchesTransformer());
    }
}

However where I'm getting stuck is inside my DispatchesTransformer:

class DispatchesTransformer
{
    protected $avaiableIncludes = [
        'product',
    ];

    public function transform($order)
    {
        return [];
    }

    public function includeProduct()
    {
        // ...
    }
}

I have an available include product I'd like to use. I don't want to make this a default include. How can I use that include?

I have tried something like this from my controller:

->parseIncludes(['dispatches', 'product'])


Solution

  • This can be achieved using the dot notation like so:

    dispatches.product

    It is actually in the documentation under including data, something I overlooked: https://fractal.thephpleague.com/transformers/