Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
L

laravel-responder

> 后端框架
Open source

A Laravel Fractal package for building API responses, giving you the power of Fractal with Laravel's elegancy.

889 stars0 likes2 views
WebsiteGitHub

About

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.

Table of Contents

  • Introduction
  • Requirements
  • Installation
  • Usage
    • Creating Responses
    • Creating Success Responses
    • Creating Transformers
    • Transforming Data
    • Creating Error Responses
    • Handling Exceptions
  • Contributing
  • Donating
  • License

Introduction

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:

php
 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:

php
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!

Requirements

This package requires:

  • PHP 7.0+
  • Laravel 5.1+ or Lumen 5.1+

Installation

To get started, install the package through Composer:

bash
composer require flugger/laravel-responder

Laravel

Register Service Provider

Append the following line to the providers key in config/app.php to register the package:

php
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.


Register Facades (optional)

If you like facades, you may also append the Responder and Transformation facades to the aliases key:

php
'Responder' => Flugg\Responder\Facades\Responder::class,
'Transformation' => Flugg\Responder\Facades\Transformation::class,

Publish Package Assets (optional)

You may additionally publish the package configuration and language file using the vendor:publish Artisan command:

bash
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.

Lumen

Register Service Provider

Add the following line to app/bootstrap.php to register the package:

php
$app->register(Flugg\Responder\ResponderServiceProvider::class);

Register Facades (optional)

You may also add the following lines to app/bootstrap.php to register the facades:

php
class_alias(Flugg\Responder\Facades\Responder::class, 'Responder');
class_alias(Flugg\Responder\Facades\Transformation::class, 'Transformation');

Publish Package Assets (optional)

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.

Usage

This documentation assumes some knowledge of how Fractal works.

Creating Responses

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:

Option 1: Inject Responder Service

You may inject the Flugg\Responder\Responder service class directly into your controller methods:

php
public function index(Responder $responder)
{
    return $responder->success();
}

You can also use the error method to create error responses:

php
return $responder->error();

Option 2: Use responder Helper

If you're a fan of Laravel's response helper function, you may like the responder helper function:

php
return responder()->success();
php
return responder()->error();

Option 3: Use Responder Facade

Optionally, you may use the Responder facade to create responses:

php
return Responder::success();
php
return Responder::error();

Option 4: Use MakesResponses Trait

Lastly, the package provides a Flugg\Responder\Http\MakesResponses trait you can use in your controllers:

php
return $this->success();
php
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.


Building Responses

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:

php
return responder()->success()->respond();
php
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:

php
return responder()->success()->respond(201, ['x-foo' => true]);
php
return responder()->error()->respond(404, ['x-foo' => false]);

Consider always using the respond method for consistency's sake.


Casting Response Data

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:

php
return responder()->success()->toArray();
php
return responder()->error()->toArray();

You also have a toCollection and toJson method at your disposal.

Decorating Response

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:

php
'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:

php
return responder()->success()->decorator(ExampleDecorator::class)->respond();
php
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;
php
\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.
php
\Flugg\Responder\Http\Responses\Decorators\EscapeHtmlDecorator::class,

Creating Success Responses

As briefly demonstrated above, success responses are created using the success method:

php
return responder()->success()->respond();

Assuming no changes have been made to the configuration, the above code would output the following JSON:

json
{
    "status": 200,
    "success": true,
    "data": null
}

Setting Response Data

The success method takes the response data as the first argument:

php
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:

php
return responder()->success(Product::where('id', 1))->respond();
php
return responder()->success(Product::first()->shipments())->respond();

The package will run the queries and convert them to collections behind the scenes.


Transforming Response Data

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.

Setting Transformer On Response

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:

php
return responder()->success(Product::all(), function ($product) {
    return ['name' => $product->name];
})->respond();

You may also transform using a dedicated transformer class:

php
return responder()->success(Product::all(), ProductTransformer::class)->respond();
php
return responder()->success(Product::all(), new ProductTransformer)->respond();

You can read more about creating dedicated transformer classes in the Creating Transformers chapter.


Binding Transformer To Model

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:

php
class Product extends Model implements Transformable {}

You can satisfy the contract by adding a transformer method that returns the corresponding transformer:

php
/**
 * 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:

php
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,
    ]);
}
`

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPapifractallaravellumen

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架