1

I have a Controller that returns all of the users likes. These likes can be from a Gig or a Track. I haves used polymorphic relationships to achieve this. Both Gigs and Tracks have their own Fractal transformer that works perfectly on their own. It would be helpful if the returned response from the likes controller was a JSON response containing both the Gigs and Tracks objects within it. I hope you understand what I mean but here is a brief example.

The response would look something like this:

{
"data": [
    {
        "id": 1,
        "user_id": 2,
        "name": "test",
        "genre": "test",
        "description": "",
        "venue": "test",
        "date": {
            "date": "-0001-11-30 00:00:00",
            "timezone_type": 3,
            "timezone": "UTC"
        },
        "lineup": "",
        "price": "0",
        "currency": "",
        "image": false,
        "attending_count": 0
    },
    {
        "id": 2,
        "user_id": 2,
        "name": "test",
        "genre": "test",
        "description": "",
        "URI" : "http://example.com/track",
    },

],
"meta": {
    "pagination": {
        "total": 2,
        "count": 2,
        "per_page": 50,
        "current_page": 1,
        "total_pages": 1,
        "links": []
    }
}
}

As you can see their are two DIFFERENT parts to the response. I would also like it to nest the arrays further so I had a track: [ and a gig: [. But that is something I will look at later.

Here's what I have so far.

    $user = User::find($userId);
    if (! $user){
        return $this->respondNotFound("This user could not be found.");
    }
    $arr = [];
    foreach ($user->likes()->get() as $like)
    {
        if($like->likeable_type == 'Gig'){
            $item = new Fractal\Resource\Item($like->likeable, new GigTransformer);
        }
        elseif($like->likeable_type == 'Track'){
            $item = new Fractal\Resource\Item($like->likeable, new TrackTransformer);
        }
        $arr[] = $item;
    }
    $paginator = Paginator::make($arr, count($arr), 50);
    return $paginator;

This returns a pagination with the correct count of items but no data.

If you don't understand anything I have said please leave a comment.

Many thanks

2 Answers 2

1

After working through it for the best part of the day I have figured it out and have learnt quite a lot about Objects and the like.

Here's what I have.

    $user = User::find($userId);
    if (! $user){
        return $this->respondNotFound("This user could not be found.");
    }
    $obj = new ArrayObject();
    $fractal = new Fractal\Manager();
    $fractal->setSerializer(new Fractal\Serializer\JsonApiSerializer());
    foreach ($user->likes()->get() as $like)
    {
        if($like->likeable_type == 'Gig'){
            $item = new Fractal\Resource\Item($like->likeable, new GigTransformer, 'gig');
        }
        elseif($like->likeable_type == 'Track'){
            $item = new Fractal\Resource\Item($like->likeable, new TrackTransformer, 'track');
        }
        $obj->append($fractal->createData($item)->toArray());
    }
    $paginator = Paginator::make((array) $obj, $obj->count(), 50);
    $response = [
        'likes' => (array) $obj,
        'meta' => [
            'pagination' => [
                'total' => $paginator->getTotal(),
                'count' => $paginator->count(),
                'per_page' => $paginator->getPerPage(),
                'current_page' => $paginator->getCurrentPage(),
                'total_pages' => $paginator->getLastPage(),
                'links' => $paginator->links(),
            ],
        ]
    ];
    return ($this->respond($response));

I should think you can see what is going on here quite easily.

I used an ArrayObject so that I could keep the Fractal Item object without type hinting it into an array and still use array functions. The Fractal Items are appended to the ArrayObject which is then paginated. I wanted to display the pagination in a particular way with likes wrapping all the user data and meta wrapping the pagination data. This respond() method is just something I use throughout my controllers to respond in JSON format.

Hopefully this will help anyone looking to do a similiar thing. I love Laravel.

0

You can put it to the transporter level where it belongs:

use League\Fractal\Resource\Item;

public function transform($item)
{
    $transformer_class = null;
    switch($item->type)
    {
        case "gig" :
            $transformer_class = new TransporterGig();
            break;
        case "track":
        default:
            $transformer_class = new TransporterTrack();
            break;
    }
    $resource = new Item($item, $transformer_class);
    return $this->currentScope->getManager()->createData($resource)->toArray()["data"];
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.