How do you go about formatting your data to send to Ember Data?

So, I’ve been toying around with Ember, I’m using Laravel on the back-end because that’s what I’m familiar with. I finally got a simple experiment working using Ember and Laravel together; however it’s very hacked together.

In Laravel I can do something convenient like this:

$posts = Post::all()->toJson();
return $posts;

…with ‘Post’ being a Model

But Ember Data requires the JSON to have a root. This was causing me an error, something like "no model was found for ‘0’ ". Googling helped me figure out what the problem was, read up on the docs here (link)

And tried this:

return '{ "post": ' . $posts . ' }';

And it worked… but obviously that’s ugly.

I wondered why the root had to be singular if it contained an array. I tried just changing ‘post’ to ‘posts’, and it still worked the same. Not exactly sure why. Does Ember automatically handle both cases?

Anyhow. I don’t currently know of any easy way to format my data that way… I mean, I could put something better together, of course, but I’m just trying to think of an end-to-end solution.

Also, I read something about the devs wanting to use jsonapi.org for a standard JSON format. That sounds interesting. It would be nice to have a standard, and then maybe people could make little helper libraries for any given language (like PHP/Laravel) that help you return the JSON in that form. At least, it seems like that’s the idea they’re going for.

What do you use for your back-end/API and how do you format it for Ember Data?

The proper way of doing this is to create a custom Adapter or Serializer depending on how much customization you need to make it Ember Data compatible. Checkout this slideshow for a summary of what Ember Data expects.

Both will work but they’re designed for different kinds of endpoints. Ember Data checks for certain JSON format to guess how to extract data. post: {} is usually returned by /posts/1 endpoint, posts: [] is returned by /posts/ endpoint.

I know this is an old thread but here’s what I found in stackexchange and preferred over other suggestions, and I would post it here if ever somebody else does look for it.

$posts = Post::all()->toArray();
return Response::json( [ 'posts' => $posts ] );
3 Likes