2

I'm trying to transform a collection of tickets with the following code

public function transform(Ticket $ticket) {
    return [
        'id' => $ticket->id,
        'title' => $ticket->title,
        'status' => $this->transformerMessage($ticket->status),
        'interactions' => 
              $this->collection(
                   $ticket->interactions,
                   new InteractionTransformer(),
                   'interactions'
              )
    ];
}

But the interactions result is always empty. Here is an example of output I'm getting:

{
  "data": [
    {
      "id": 1,
      "title": "Earum repudiandae corporis sapiente at odit itaque ratione.",
      "status": "Open",
      "interactions": {}
    },
    {
      "id": 2,
      "title": "Odit impedit vitae quo sit molestiae eius.",
      "status": "Open",
      "interactions": {}
    },
    {
      "id": 3,
      "title": "Fuga cum corrupti ut.",
      "status": "Open",
      "interactions": {}
    }
  ]
}

if I try to die and dump the $ticket->interactions variable, I get a Collection of 5 items (which proves the variable isn't empty).

What am I doing wrong here?

Thanks for your attention.

Marco Aurélio Deleu
  • 4,279
  • 4
  • 35
  • 63

2 Answers2

1

Try this instead. Callback referencing the dingo transform:

public function transform(Ticket $ticket) {
    $output = $ticket->interactions;
    $trans = new InteractionTransformer();
    return [
        'id' => $ticket->id,
        'title' => $ticket->title,
        'status' => $this->transformerMessage($ticket->status),
        'interactions' => 
              $ticket->interactions->transform(
                 function($i) use ($trans) {
                    return $trans->transform($i);
                 }
              )
    ];
}
0

The $this in your collection call is referring to the transformer which inherits from TransformerAbstract which creates a Collection from a Resource type.

Try adding ->getData() to the end to pull the REAL collection from the Dingo Resource Collection.

public function transform(Ticket $ticket) {
    return [
        'id' => $ticket->id,
        'title' => $ticket->title,
        'status' => $this->transformerMessage($ticket->status),
        'interactions' => 
              $this->collection(
                   $ticket->interactions,
                   new InteractionTransformer(),
                   'interactions'
              )->getData()
    ];
}
Pankaj
  • 9,749
  • 32
  • 139
  • 283