A Laravel Fractal package for building API responses, giving you the power of Fractal with Laravel's elegancy.
A Laravel Fractal package for building API responses, giving you the power of Fractal with Laravel's elegancy.
Laravel Responder is a package for building API responses, integrating Fractal into Laravel and Lumen. It can transform your data using transformers, create and serialize success- and error responses, handle exceptions and assist you with testing your responses.
Laravel lets you return models directly from a controller method to convert it to JSON. This is a quick way to build APIs but leaves your database columns exposed. Fractal, a popular PHP package from The PHP League, solves this by introducing transformers. However, it can be a bit cumbersome to integrate into the framework as seen below:
public function index()
{
$resource = new Collection(User::all(), new UserTransformer());
return response()->json((new Manager)->createData($resource)->toArray());
}Not that bad, but we all get a little spoiled by Laravel's magic. Wouldn't it be better if we could refactor it to:
public function index()
{
return responder()->success(User::all())->respond();
}The package will allow you to do this and much more. The goal has been to create a high-quality package that feels like native Laravel. A package that lets you embrace the power of Fractal, while hiding it behind beautiful abstractions. There has also been put a lot of focus and thought to the documentation. Happy exploration!
This package requires:
To get started, install the package through Composer:
composer require flugger/laravel-responderAppend the following line to the providers key in config/app.php to register the package:
Flugg\Responder\ResponderServiceProvider::class,The package supports auto-discovery, so if you use Laravel 5.5 or later you may skip registering the service provider and facades as they will be registered automatically.
If you like facades, you may also append the Responder and Transformation facades to the aliases key:
'Responder' => Flugg\Responder\Facades\Responder::class,
'Transformation' => Flugg\Responder\Facades\Transformation::class,You may additionally publish the package configuration and language file using the vendor:publish Artisan command:
php artisan vendor:publish --provider="Flugg\Responder\ResponderServiceProvider"This will publish a responder.php configuration file in your config folder. It will also publish an errors.php file inside your lang/en folder which can be used for storing error messages.
Add the following line to app/bootstrap.php to register the package:
$app->register(Flugg\Responder\ResponderServiceProvider::class);You may also add the following lines to app/bootstrap.php to register the facades:
class_alias(Flugg\Responder\Facades\Responder::class, 'Responder');
class_alias(Flugg\Responder\Facades\Transformation::class, 'Transformation');Seeing there is no vendor:publish command in Lumen, you will have to create your own config/responder.php file if you want to configure the package.
This documentation assumes some knowledge of how Fractal works.
The package has a Responder service class, which has a success and error method to build success- and error responses respectively. To use the service and begin creating responses, pick one of the options below:
Responder ServiceYou may inject the Flugg\Responder\Responder service class directly into your controller methods:
public function index(Responder $responder)
{
return $responder->success();
}You can also use the error method to create error responses:
return $responder->error();responder HelperIf you're a fan of Laravel's response helper function, you may like the responder helper function:
return responder()->success();return responder()->error();Responder FacadeOptionally, you may use the Responder facade to create responses:
return Responder::success();return Responder::error();MakesResponses TraitLastly, the package provides a Flugg\Responder\Http\MakesResponses trait you can use in your controllers:
return $this->success();return $this->error();Which option you pick is up to you, they are all equivalent, the important thing is to stay consistent. The helper function (option 2) will be used for the remaining of the documentation.
The success and error methods return a SuccessResponseBuilder and ErrorResponseBuilder respectively, which both extend an abstract ResponseBuilder, giving them common behaviors. They will be converted to JSON when returned from a controller, but you can explicitly create an instance of Illuminate\Http\JsonResponse with the respond method:
return responder()->success()->respond();return responder()->error()->respond();The status code is set to 200 by default, but can be changed by setting the first parameter. You can also pass a list of headers as the second argument:
return responder()->success()->respond(201, ['x-foo' => true]);return responder()->error()->respond(404, ['x-foo' => false]);Consider always using the respond method for consistency's sake.
Instead of converting the response to a JsonResponse using the respond method, you can cast the response data to a few other types, like an array:
return responder()->success()->toArray();return responder()->error()->toArray();You also have a toCollection and toJson method at your disposal.
A response decorator allows for last minute changes to the response before it's returned. The package comes with two response decorators out of the box adding a status and success field to the response output. The decorators key in the configuration file defines a list of all enabled response decorators:
'decorators' => [
\Flugg\Responder\Http\Responses\Decorators\StatusCodeDecorator::class,
\Flugg\Responder\Http\Responses\Decorators\SuccessFlagDecorator::class,
],You may disable a decorator by removing it from the list, or add your own decorator extending the abstract class Flugg\Responder\Http\Responses\Decorators\ResponseDecorator. You can also add additional decorators per response:
return responder()->success()->decorator(ExampleDecorator::class)->respond();return responder()->error()->decorator(ExampleDecorator::class)->respond();The package also ships with some situational decorators disabled by default, but which can be added to the decorator list:
PrettyPrintDecorator decorator will beautify the JSON output;\Flugg\Responder\Http\Responses\Decorators\PrettyPrintDecorator::class,EscapeHtmlDecorator decorator, based on the "sanitize input, escape output" concept, will escape HTML entities in all strings returned by your API. You can securely store input data "as is" (even malicious HTML tags) being sure that it will be outputted as un-harmful strings. Note that, using this decorator, printing data as text will result in the wrong representation and you must print it as HTML to retrieve the original value.\Flugg\Responder\Http\Responses\Decorators\EscapeHtmlDecorator::class,As briefly demonstrated above, success responses are created using the success method:
return responder()->success()->respond();Assuming no changes have been made to the configuration, the above code would output the following JSON:
{
"status": 200,
"success": true,
"data": null
}The success method takes the response data as the first argument:
return responder()->success(Product::all())->respond();It accepts the same data types as you would normally return from your controllers, however, it also supports query builder and relationship instances:
return responder()->success(Product::where('id', 1))->respond();return responder()->success(Product::first()->shipments())->respond();The package will run the queries and convert them to collections behind the scenes.
The response data will be transformed with Fractal if you've attached a transformer to the response. There are two ways to attach a transformer; either explicitly by setting it on the response, or implicitly by binding it to a model. Let's look at both ways in greater detail.
You can attach a transformer to the response by sending a second argument to the success method. For instance, below we're attaching a simple closure transformer, transforming a list of products to only output their names:
return responder()->success(Product::all(), function ($product) {
return ['name' => $product->name];
})->respond();You may also transform using a dedicated transformer class:
return responder()->success(Product::all(), ProductTransformer::class)->respond();return responder()->success(Product::all(), new ProductTransformer)->respond();You can read more about creating dedicated transformer classes in the Creating Transformers chapter.
If no transformer is set, the package will search the response data for an element implementing the Flugg\Responder\Contracts\Transformable interface to resolve a transformer from. You can take use of this by implementing the Transformable interface in your models:
class Product extends Model implements Transformable {}You can satisfy the contract by adding a transformer method that returns the corresponding transformer:
/**
* Get a transformer for the class.
*
* @return \Flugg\Responder\Transformers\Transformer|string|callable
*/
public function transformer()
{
return ProductTransformer::class;
}You're not limited to returning a class name string, you can return a transformer instance or closure transformer, just like the second parameter of the success method.
Instead of implementing the Transformable contract for all models, an alternative approach is to bind the transformers using the bind method on the TransformerResolver class. You can place the code below within AppServiceProvider or an entirely new TransformerServiceProvider:
use Flugg\Responder\Contracts\Transformers\TransformerResolver;
public function boot()
{
$this->app->make(TransformerResolver::class)->bind([
\App\Product::class => \App\Transformers\ProductTransformer::class,
\App\Shipment::class => \App\Transformers\ShipmentTransformer::class,
]);
}
`No open issues yet, or sync has not completed.