Is there an elegant way to nest transformers for relationship use? I'm looking to build a REST interface that allows for collections to conditionally include relationship models. So far I've been marginally successful, but it seems to break down a bit when it comes to the transformers (I'll admit I'm a bit new to Laravel 5.1 and Dingo). I'm looking to keep this as DRY as possible, so that if relationships or attributes change in the future it's pretty easy to change.
For example, a simple scenario where a user may receive one or more messages (user hasMany received messages) 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'd like to nest / apply a MesagesTransformer to the related received messages for output formatting so that all REST output remains consistent across all relationships. Is this possible? Thanks!