Laravel 5.1, Dingo - Nested Transformers
Is there an elegant way to embed transformers to use relationships? I'm looking to create a REST interface that allows collections to conditionally include relationship models. I've been a bit successful so far, but it seems to have crashed a bit when it comes to transformers (I admit I'm a bit new to Laravel 5.1 and Dingo). I want this to be as dry as possible, so that if the relationship or attributes change in the future, it's pretty easy to change.
For example, a simple scenario where a user can receive one or more messages (the user has many messages received), I can do the following in the UserTransformer:
<?php
namespace App\Transformers;
use App\Models\User;
use League\Fractal;
class UserTransformer extends Fractal\TransformerAbstract
{
public function transform(User $user)
{
// Transform the basic model
$returnUser = [
'id' => (int) $user->id,
'email' => $user->email,
'role' => $user->role,
'status' => $user->status,
'links' => [
[
'rel' => 'self',
'uri' => '/users/'.$user->id
]
]
];
// Transform relationships, but only if they exist and are requested
if (isset($user->receivedMessages))
{
$returnUser['received_messages'] = [];
foreach ($user->receivedMessages as $msg)
{
$returnUser['received_messages'][] = [
'id' => $msg->id,
'read' => $msg->read,
'content' => $msg->content
];
}
}
return $returnUser;
}
}
In this case, I would like to nest / apply the MesagesTransformer to the corresponding received messages to format the output so that all REST output remains consistent in every way. Is it possible? Thank!
source to share