Skip to content

Instantly share code, notes, and snippets.

@puncoz
Last active July 3, 2019 11:39
Show Gist options
  • Save puncoz/501037b37987b62a04941acae942d9f7 to your computer and use it in GitHub Desktop.
Save puncoz/501037b37987b62a04941acae942d9f7 to your computer and use it in GitHub Desktop.
<?php
class UserController
{
public function lists()
{
// Create a fractal instance
$fractal = new \League\Fractal\Manager();
// to enable links support, we need to set a baseUrl on serializer
$baseUrl = url('/api');
$fractal->setSerializer(new \League\Fractal\Serializer\JsonApiSerializer($baseUrl));
// Get Data from your database model
$users = \App\User::paginate(25);
// Pass this array (collection) into a resource, which will also have a "Transformer"
// This "Transformer" can be a callback or a new instance of a Transformer object
// Important, notice the Resource Key in the third parameter:
$resource = new \League\Fractal\Resource\Collection($users, new \App\UserTransformer(), 'users');
// Turn that into a structured array (handy for XML views or auto-YAML converting)
$data = $fractal->createData($resource)->toArray();
// OR, Turn all of that into a JSON string
// $data = $fractal->createData($resource)->toJson();
return $data;
}
}
<?php
class UserTransformer extends League\Fractal\TransformerAbstract
{
$defaultIncludes = ['posts'];
public function transform(\App\User $user): array
{
return [
'id' => (int) $user->id,
'name' => $user->firstname . ' ' . $user->lastname,
'dob' => $user->bob,
];
}
public function includePosts(\App\User $user): \League\Fractal\Resource\Collection
{
return $this->collection($user->posts, new \App\PostTransformer(), 'posts');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment