Skip to content
On this page

Transformer

Transformers gives the flexibility to create a format for JSON response that is needed. By using transformers we can also do type casting, pagination results, and also nest relationships.

Response Transformer

class CategoriesTransformer extends TransformerAbstract
{
    public function transform(Category $category)
    {
        return [
            'id' => $category->id,
            'categoryName' => $category->name,
            'categoryAttribute' => $category->attributes,
            'description' => $category->dexcription,
            'status' => $category->status,
            'subCategory' => $category->child()->get() ?? null,
        ];
    }
}

Default Includes

Default includes are defined in a property on the transformer. This is used to include additional data in the response from another transformer.

protected $defaultIncludes = [
    'product'
];

public function includeProduct(Category $category)
{
    $product = $category->product;

    return $this->item($product, new ProductTransformer);
}