Last active
August 17, 2018 23:06
-
-
Save ipalaus/8588411 to your computer and use it in GitHub Desktop.
Using cursor instead of pagination with Fractal. IE: GET /users?cursor=5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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()); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
?? eturn $this->respondWithArray($rootScope->toArray()); ?? I can not find this line of code APiController