TheWebs TheWebs - 5 months ago 32
JSON Question

PHP Fractals (transformers) outputs some strange json

So I don't know if this is the norm, but this json doesn't look easy to use, especially for front end developers.

So using these docs I did a default include for posts on a blog, the transformers are:

<?php

namespace App\Etis\Domain\Transformers\Blog;

use League\Fractal\TransformerAbstract;
use App\Etis\Domain\Entities\BlogsEntity;
use Carbon\Carbon;
use App\Etis\Domain\Transformers\Blog\Posts\PostsTransformer;

class BlogsTransformer extends TransformerAbstract {

protected $defaultIncludes = [
'posts'
];

public function transform(BlogsEntity $blog) {

return [
'id' => $blog->id,
'belongs_to_user' => $blog->user_id,
'title' => $blog->title,
'created_at' => $blog->created_at->format(Carbon::ISO8601),
'updated_at' => $blog->updated_at->format(Carbon::ISO8601)
];
}

public function includePosts(BlogsEntity $blog) {
$posts = $blog->posts;

return $this->collection($posts, new PostsTransformer);
}
}


The above is the blog transformer, which as we can see includes posts, so lets see that transformer:

<?php

namespace App\Etis\Domain\Transformers\Blog\Posts;

use League\Fractal\TransformerAbstract;
use App\Etis\Domain\Entities\PostsEntity;
use Carbon\Carbon;

class PostsTransformer extends TransformerAbstract {

public function transform(PostsEntity $post) {
return [
'id' => $post->id,
'title' => $post->title,
'content' => $post->content,
'blog_id' => $post->blog_id,
'published' => $post->published,
'slug' => $post->slug,
'saved' => $post->saved,
'created_at' => $post->created_at->format(Carbon::ISO8601),
'updated_at' => $post->updated_at->format(Carbon::ISO8601)
];
}
}


Super simple, nothing complicated.

{
data:[
{
type:"blogs",
id:"2",
attributes:{
belongs_to_user:2,
title:"Everymans Thoughts",
created_at:"2016-04-28T16:14:48+0000",
updated_at:"2016-04-28T16:14:48+0000"
},
relationships:{
posts:{
data:[
{
type:null,
id:"2"
},
{
type:null,
id:"3"
}
]
}
}
},
{
type:"blogs",
id:"1",
attributes:{
belongs_to_user:1,
title:"GNI2BOWLHy",
created_at:"2016-04-22T19:56:23+0000",
updated_at:"2016-04-22T19:56:23+0000"
},
relationships:{
posts:{
data:[
{
type:null,
id:"1"
}
]
}
}
}
],
included:[
{
type:null,
id:"2",
attributes:{
title:"Sample Blog",
content:"<p><img src=" http://lorempixel.com/900/400/" alt="Image" /></p> <p>Lorem markdownum Hymenaee. <em>Triste</em> tamen? Sed herbas opibusque ratem placebant timor Trachinia libera verba opem teste aquaticus ne est paulum ipse Aesonides?</p> <p>Lorem markdownum Hymenaee. <em>Triste</em> tamen? Sed herbas opibusque ratem placebant timor Trachinia libera verba opem teste aquaticus ne est paulum ipse Aesonides?</p> <p>Lorem markdownum Hymenaee. <em>Triste</em> tamen? Sed herbas opibusque ratem placebant timor Trachinia libera verba opem teste aquaticus ne est paulum ipse Aesonides? if (operation_bitrate_cron.gpsOsEmulation(kde_terahertz_qwerty,
gigabyte( mask) + surfaceKeywords)) {
partition_whois += 2 + -2;
} memory *= portalLink; hdmi_tween = user.signature(mcaBooleanBatch * 54,
header(driveDatabase),
ip_latency);</p> <h2>Prope eripe consorte natis virgo appellant venisset</h2> <p>Gente cum audito nymphae <a href="http://hipstermerkel.tumblr.com/">levati veri ictibus</a>,
aut arida,
quantumque. Modo insistit <strong>quidem</strong>:satis parvos edaci totiens spectare,
alto huic suis facitis nondum. Sorores <a href="http://www.thesecretofinvisibility.com/">oblita</a>,
in ait pascas,
tantum iam; speciem,
labefactum. Postquam <strong>ager</strong> Talibus turba non uberrima,
pulchro et quibus sententia munitos dum,
et aquarum dubiae,
pars. Terga vellet de Emathion Phlegyis Circes peremptam siccat,
me suis Prochytenque.</p> <h2>A nostra</h2> <p>Paternos nequeunt,
rapta,
velles; fugisse his tergo plurima! Veni cognita cavernis et tergo interrumpente terra; nec ortus videtur cumque nunc! Dubitanti frater nunc moras tuque,
est litore Plura. Haec color Ceres nitidis oculus,
cum squamae,
crede australem in abiere,
te plebemque lentum!</p> <h2>Ab haec condi et suum memorabile nequiquam</h2> <p>Vulneribus docuique ridentem monstravit et <a href="http://gifctrl.com/">intacta vomit terroris</a> pia ille festumque iterque nunc,
quamvis. Subito quid. Ad pariente mihi facto hortatibus nisi tamen pulsat dolor ac se,
ille in orant quodcumque guttur,
rite.</p> <blockquote> <p>Vultus Aiaci his picto,
comitique huic,
ferro:est certi,
sententia commissas mater. Superi tabuerint terras intravit inertes conorque aurum reus mentas caelo ut et sintque: <em>feruntur usus</em>. <a href="http://zombo.com/">Illa avsis noxque</a>,
sua Bacchumque comminus positus. Cur igne paulatim?</p> </blockquote> <p>Non gauderet,
vellere,
auro halitus,
fortuna non Picus me alios Cerberei potentes. Aquis praelatus soceri densa!</p> ",
blog_id:2,
published:true,
slug:"sample-blog",
saved:false,
created_at:"2016-04-28T16:16:52+0000",
updated_at:"2016-04-30T18:25:49+0000"
}
},
{
type:null,
id:"3",
attributes:{
title:"asdasdasda",
content:"<p>asdasdsadsa</p> ",
blog_id:2,
published:false,
slug:"asdasdasda",
saved:true,
created_at:"2016-05-14T16:53:12+0000",
updated_at:"2016-05-14T16:53:12+0000"
}
},
{
type:null,
id:"1",
attributes:{
title:"yTxxDi0EwD",
content:"YQzrVXMB5bXepspPNp0RLaCoqXYrWPgEvcZxcISrGcFBPFxic8KsdRYpvMLPlZenoJIlI2fpSwxbeTMtWDHZW8Z5fnUBBn6lTiVz",
blog_id:1,
published:true,
slug:"ytxxdi0ewd",
saved:false,
created_at:"2016-04-22T19:56:23+0000",
updated_at:"2016-04-22T19:56:23+0000"
}
}
],
meta:{
pagination:{
total:2,
count:2,
per_page:15,
current_page:1,
total_pages:1,
links:[

]
}
}
}


How do I use these transformers to get said JSON?

I have a controller method:

public function getBlogs() {
$manager = new Manager();
$manager->setSerializer(new JsonApiSerializer());

if (\Auth::check()) {
$paginatedBlogs = BlogsEntity::orderBy('created_at', 'desc')->paginate();
$blogs = $paginatedBlogs->getCollection();

$resource = new Collection($blogs, new BlogsTransformer(), 'blogs');
$resource->setPaginator(new IlluminatePaginatorAdapter($paginatedBlogs));

return $manager->createData($resource)->toArray();
} else {
return response()->json(['error_message' => 'You cannot access this route.']);
}
}



  1. So why am I getting the really ugly JSON thats like impossible to use?

  2. Why are the posts not nested under their respective
    blogs?


Answer

$manager->setSerializer(new JsonApiSerializer()); sets Fractal to output JSON-API compliant JSON, which has a very particular spec (http://jsonapi.org/). If you don't want its complicated (but standardized, which is potentially very useful to front-end folks) output, use a different (like the default one) serializer.