Ad

How To Force Restangular's GetList To Work With Laravel 5's Pagination Object?

I have a page where I want to display user's posts paginated. For back-end I use Laravel's resource controllers and on the front-end Restangular services.

So back-end implementation looks like this:

// url is /users/0/posts
public function index(Post $post)
{
    return $post->whereUserId(\Auth::id())->paginate(20);
}

Front-end looks like this:

/*
 * posts.service.js
 */
angular.module('app.services')
    .service('posts', Posts);

Posts.$inject = ['Restangular'];

function Posts(Restangular) {
    return Restangular.service('posts', Restangular.one('users', 0));
}



/*
 * posts.controller.js
 */
angular.module('koodzo.controllers')
    .controller('PostsController', PostsController);

ContentController.$inject = ['posts'];

function PostController(posts) {
    var vm = this;

    vm.posts = posts.getList()
        .then(function(response) {
            vm.pagination = response;
            vm.posts = response.data;
        });
}

So, obviously, this doesn't work, because Restangular's getList expects to receive an array from the server to restangularize it, but Laravel's paginator returns an object and the array is in the data field of the object.

The question is how to make Restangular see that response.data is the array that it needs?

Ad

Answer

In order to make Laravel's paginated response work with Restangular's getList(), you need to register a response interceptor that will return whatever you get in response.data as response.

The following code will do the trick:

app.module('yourModule').config(function(RestangularProvider) {
  RestangularProvider.addResponseInterceptor(parseApiResponse);

  function parseApiResponse(data, operation) {
    var response = data;

    if (operation === 'getList' && data.data) {
      response = data.data;
      response.metadata = _.omit(data, 'data');
    }

    return response;
  }
});

Your calls to getList() will give you the data object directly. Additionally, you'll be able to access the pagination metadata that Laravel returns - it will be stored in metadata property of your response.

Ad
source: stackoverflow.com
Ad