Skip to content

Instantly share code, notes, and snippets.

@ipalaus
Last active August 17, 2018 23:06
Show Gist options
  • Save ipalaus/8588411 to your computer and use it in GitHub Desktop.
Save ipalaus/8588411 to your computer and use it in GitHub Desktop.
Using cursor instead of pagination with Fractal. IE: GET /users?cursor=5
<?php
use League\Fractal\Manager;
use League\Fractal\Resource\Collection;
use League\Fractal\Resource\Item;
use League\Fractal\Cursor\CursorInterface;
class ApiController extends Controller
{
public function __construct()
{
$this->fractal = new Manager;
$this->fractal->setRequestedScopes(explode(',', Input::get('include')));
}
protected function respondWithCursor($collection, $callback, CursorInterface $cursor)
{
$resource = new Collection($collection, $callback);
$resource->setCursor($cursor);
$rootScope = $this->fractal->createData($resource);
return $this->respondWithArray($rootScope->toArray());
}
}
{
"data": [
{
"id": 6,
"name": "Lennie Raynor PhD"
},
{
"id": 7,
"name": "Duncan Raynor"
},
{
"id": 8,
"name": "clockman"
},
{
"id": 9,
"name": "Gerard Marks DDS"
},
{
"id": 10,
"name": "josefina32"
}
],
"cursor": {
"current": 5,
"next": 10,
"count": 5
}
}
{
"data": [
{
"id": 1,
"name": "Isern Palaus"
},
{
"id": 2,
"name": "Lorem Ipsum"
},
{
"id": 3,
"name": "Javi Martinez"
},
{
"id": 4,
"name": "lowe.yasmin"
},
{
"id": 5,
"name": "abshire.durward"
}
],
"cursor": {
"current": 0,
"next": 5,
"count": 5
}
}
<?php
use League\Fractal\Cursor\Cursor;
class UsersController extends ApiController
{
public function index()
{
$current = Input::get('cursor', false);
$users = new User;
if ($current and is_numeric($current)) {
$users = $users->where('id', '>', $current);
}
$users = $users->take(20)->get();
$cursor = new Cursor($current, $users->last()->id, $users->count());
return $this->respondWithCursor($users, new UserTransformer, $cursor);
}
}
@developcreativo
Copy link

developcreativo commented Jul 18, 2017

?? eturn $this->respondWithArray($rootScope->toArray()); ?? I can not find this line of code APiController

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment