jotaen / fractal-response
Using Transformers in Laravel Responses
Installs: 2 960
Dependents: 0
Suggesters: 0
Security: 0
Stars: 3
Watchers: 3
Forks: 0
Open Issues: 0
Requires
- php: >=5.4.0
- illuminate/html: ~5.0
- league/fractal: ~0.12
This package is not auto-updated.
Last update: 2024-10-30 07:58:31 UTC
README
With FractalReponse you can easily use Fractal Transformers to serialize Laravel Reponse objects.
The FractalResponse
class inherits from Illuminate\Http\Response
. In addition, you pass your Leage\Fractal
-transformer to the with()
-method, so that your response gets automatically serialized the way you wish. This is especially helpful when writing REST services, where you have to provide a defined data structure.
Installation:
The easiest way is to add FractalResponse as dependency to your composer.json:
require: { "jotaen/fractal-response": "1.x" }
Example:
<?php namespace App\Http\Controllers; use League\Fractal; use Laravel\Lumen\Routing\Controller as BaseController; use FractalResponse\FractalResponse as Response; class Controller extends BaseController { public function showOneBook() { $book = new Book(); $response = new Response($book, 200); $response->with(new BookTransformer()); return $response; } public function showSeveralBooks() { $books = [ new Book(), new Book() ]; $response = new Response($books, 200); $response->with(new BookTransformer()); return $response; } } class Book { public function title() { return 'Help, i am an elephant!'; } } class BookTransformer extends Fractal\TransformerAbstract { public function transform($foo) { return [ 'Title' => $foo->title(), ]; } }