Include related table from pivot table in Fractal's Transformers

210 Views Asked by At

In my Laravel project, I have 4 tables:

  • location
  • location_product
  • product
  • status

location_product is the intermediate table between location and product and it has a foreign key status pointing to the product_status table.

I'm using Fractal's transformers to transform my models:

    //Filter the products
    $products = $location->products()->unarchived()->get();

    return $this->response()->collection($products, new ProductDetailsTransformer());

and in my ProductDetailsTransformer.php, I want to include the status from the intermediate table using '''defaultIncludes''':

/**
 * List of resources to automatically include
 */
protected $defaultIncludes = [
    'status',
];

public function includeStatus(Product $product) {
    return $this->item($product->pivot->status, new ProductStatusTransformer());
}

but I receive an

Call to undefined relationship [status] on model [App\Models\Product].

How can I correctly include the status table using Fractal's transformers?

At the moment, I'm using the following:

public function transform(Product $product) {
    return [
        'id' => (int)$product->id,
        'name' => $product->name,
        'amount' => $product->pivot->amount,
        'delivery_on_site' => (bool)$product->pivot->delivery_on_site,
        'status' => [
            'id' => $product->pivot->status->id,
            'name' => $product->pivot->status->name
        ]
    ];
}

But I'd like to use a Transformer if that's possible for the status.

0

There are 0 best solutions below