3

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!

John Jemsek
  • 61
  • 1
  • 4
  • I should mention that everything seems to work peachy with singular objects and Laravel's standard attributes handling, but I'm using transformations for pagination on collections and that is mostly where this comes into play. – John Jemsek Jul 20 '15 at 01:26

1 Answers1

3

I was able to find the answer to my question here: http://fractal.thephpleague.com/transformers/.

John Jemsek
  • 61
  • 1
  • 4