macmotp's avatar

L5 creating API with pagination - Issue

I am trying to create an API with Laravel 5 and in order to refresh my memory for a good architecture I followed again the "Incremental APIs" series. Everything worked perfectly until I tried to paginate my results, this is the error I have (I duplicate my code for help using the same situation as Jeffrey did so you will find 'Lessons' and 'title'):


ErrorException in LessonTransformer.php line 12: Illegal string offset 'title' at HandleExceptions->handleError('2', 'Illegal string offset 'title'', '/.../app/Transformers/LessonTransformer.php', '12', array('lessons' => 'http://.../api/v1/lessons/?page=2')) in LessonTransformer.php line 12

In my controller:


public function index(LessonTransformer $lessonTransformer) { $limit = Input::get('limit', 10); $lessons = Lesson::paginate($limit); return $this->respond([ 'lessons' => $lessonTransformer->transformCollection($lessons) ]); }

Only difference you can find is that I index the array with 'lessons' and not with 'data'. Also, I repeat, if in my controller I use Lesson::all() it works. it doesn't work the ->all() method though so I simply used ->toArray().

Hope someone can help, I don't know if it is my mistake or not, or if the issue is in L5

0 likes
4 replies
macmotp's avatar

abstract class Transformer { /** * Transform a collection of items * * @param array $items * @return array */ public function transformCollection(array $items) { return array_map([$this, 'transform'], $items); } public abstract function transform($item); } class LessonTransformer extends Transformer { /** * @param $lesson * @return array */ public function transform($lesson) { return [ 'title' => $lesson['title'], 'description' => $lesson['description'] ]; } }
macmotp's avatar

@thawheinthit I had this issue while L5 was still in beta. Anyway it totally works now: in your controller just add ->all() method after your collection when passing to the transformCollection function:


public function index(LessonTransformer $lessonTransformer)
 {
    $limit = Input::get('limit', 10);

    $lessons = Lesson::paginate($limit);

    return $this->respond([
   'lessons' => $lessonTransformer->transformCollection($lessons->all())
    ]);
 }

1 like

Please or to participate in this conversation.