Question

I created an API for my various SPA's using a Laravel resource controller that works like a charm. While BackboneJS has no problem with the default JSON response, EmberJS expects the result wrapped in a singular and plural named JSON object depending on if it's fetching a single model or a collection of models.

What I already know

  • Convert the JSON result to an array wrap it and convert it back to JSON.
  • Wrapping every result in an object.
  • Change the result comming from the database call to an array with setFetchMode(PDO::FETCH_ASSOC);.

Question
How to properly (using the cheapest process) create the wrapped JSON responses, so without converting the results back and forth between JSON, Arrays or Objects?

A snippit from the Laravel resource controller:

<?php

class ResourceController extends Controller {

     ...

     /**
        * Display a listing of the resource.
        *
        * @return Response
        */
     public function index() {
            return Model::all();
     }


     /**
        * Display the specified resource.
        *
        * @param  int  $id
        * @return Response
        */
     public function show($id) {
            return Model::find($id);
     }

     ...

}
Was it helpful?

Solution

This will wrap the original Eloquent database result for a Laravel application with a database configured as "fetch" => PDO::FETCH_CLASS. It creates a new object of Illuminate\Database\Eloquent\Collection and wraps the Eloquent result in a models property. This way it's formatted properly for using it with Ember data without any conversions.

/**
 * Display a listing of the resource.
 *
 * @return Response
 */
public function index() {
   $index = new Illuminate\Database\Eloquent\Collection;
   $index['models'] = Model::all();
   return $index;
}

OTHER TIPS

You can do that with following structure. Always, return your json response in wrapped format like(I assumed you have User model);

{
    "user": [
        {"name": "Hüseyin"},
        {"surname": "BABAL"},
        {"title": "Software Developer"}
    ]
}

This is suitable for ember.js. For backbone.js, you need to do some extra simple job like following;

var User = Backbone.Collection.extend({
    model: User, 
    url: '/api/userInfo',
    parse: function(response) {
            return response.user;
        });
    }
});

By doing this, you will only one format rest service, and you just need to do some extra job for only backbone.js

Update:

Think about index action, you can do that like;

public function index() {
    return Response::json(array("user" => Model::all()));
}

Result will be wraped with "user", you can use response as json on frontend. The result will be;

{
    "user": [
        {...},
        {...}
    ]
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top