1. Go to this page and download the library: Download spatie/laravel-fractal library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
spatie / laravel-fractal example snippets
use League\Fractal\Manager;
use League\Fractal\Resource\Collection;
$books = [
['id' => 1, 'title' => 'Hogfather', 'characters' => [...]],
['id' => 2, 'title' => 'Game Of Kill Everyone', 'characters' => [...]]
];
$manager = new Manager();
$resource = new Collection($books, new BookTransformer());
$manager->parseIncludes('characters');
$manager->createData($resource)->toArray();
return [
/*
* The default serializer to be used when performing a transformation. It
* may be left empty to use Fractal's default one. This can either be a
* string or a League\Fractal\Serializer\SerializerAbstract subclass.
*/
'default_serializer' => '',
/* The default paginator to be used when performing a transformation. It
* may be left empty to use Fractal's default one. This can either be a
* string or a League\Fractal\Paginator\PaginatorInterface subclass.*/
'default_paginator' => '',
/*
* League\Fractal\Serializer\JsonApiSerializer will use this value to
* as a prefix for generated links. Set to `null` to disable this.
*/
'base_url' => null,
/*
* If you wish to override or extend the default Spatie\Fractal\Fractal
* instance provide the name of the class you want to use.
*/
'fractal_class' => Spatie\Fractal\Fractal::class,
'auto_
$books = fractal($books, new BookTransformer())->toArray();
return response()->json($books);
return fractal($books, new BookTransformer())->respond();
return fractal($books, new BookTransformer())->respond(403, [
'a-header' => 'a value',
'another-header' => 'another value',
]);
return fractal($books, new BookTransformer())->respond(200, [], JSON_PRETTY_PRINT);
use Illuminate\Http\JsonResponse;
return fractal($books, new BookTransformer())->respond(function(JsonResponse $response) {
$response
->setStatusCode(403)
->header('a-header', 'a value')
->withHeaders([
'another-header' => 'another value',
'yet-another-header' => 'yet another value',
]);
});
use Spatie\Fractal\Fractal;
Fractal::macro('stats', function ($stats) {
// transform the passed stats as necessary here
return $this->addMeta(['stats' => $stats]);
});
fractal($books, new BookTransformer())->stats(['runtime' => 100])->respond();