PHPackages                             timacdonald/multiformat-response-objects - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. timacdonald/multiformat-response-objects

ActiveLibrary[API Development](/categories/api)

timacdonald/multiformat-response-objects
========================================

A response object that handles multiple response formats within the one controller

v1.0.0(6y ago)664932[1 PRs](https://github.com/timacdonald/multiformat-response-objects/pulls)MITPHPPHP ^7.2CI failing

Since Jul 14Pushed 5y ago1 watchersCompare

[ Source](https://github.com/timacdonald/multiformat-response-objects)[ Packagist](https://packagist.org/packages/timacdonald/multiformat-response-objects)[ RSS](/packages/timacdonald-multiformat-response-objects/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (1)Dependencies (5)Versions (6)Used By (0)

Multi-format Response Object for Laravel
========================================

[](#multi-format-response-object-for-laravel)

[![Latest Stable Version](https://camo.githubusercontent.com/0f02def53d1407b96499935690b2fadbba989aea281bf01c098614080c4057a6/68747470733a2f2f706f7365722e707567782e6f72672f74696d6163646f6e616c642f6d756c7469666f726d61742d726573706f6e73652d6f626a656374732f762f737461626c65)](https://packagist.org/packages/timacdonald/multiformat-response-objects) [![Total Downloads](https://camo.githubusercontent.com/b53ddb155d0f95b48dcb51464cd806e16684554eaf72ffcc53f143f7a50af21a/68747470733a2f2f706f7365722e707567782e6f72672f74696d6163646f6e616c642f6d756c7469666f726d61742d726573706f6e73652d6f626a656374732f646f776e6c6f616473)](https://packagist.org/packages/timacdonald/multiformat-response-objects) [![License](https://camo.githubusercontent.com/4aad63d00925b5a1b69bddc8df4d245aa623ea017b21b00748b5b21cbed5e832/68747470733a2f2f706f7365722e707567782e6f72672f74696d6163646f6e616c642f6d756c7469666f726d61742d726573706f6e73652d6f626a656374732f6c6963656e7365)](https://packagist.org/packages/timacdonald/multiformat-response-objects)

In some situations you may want to support multiple return formats (HTML, JSON, CSV, XLSX) for the one endpoint and controller. This package gives you a base class that helps you return different formats of the same data. It supports specifying the return format as a file extension or as an `Accept` header. It also allows you to have shared and format specific logic, all while sharing the same route and controller.

Installation
------------

[](#installation)

You can install using [composer](https://getcomposer.org/) from [Packagist](https://packagist.org/packages/timacdonald/multiformat-response-objects)

```
$ composer require timacdonald/multiformat-response-objects

```

Getting started
---------------

[](#getting-started)

This package is designed to help if you have ever created a controller that looks like this...

```
class UserController
{
    public function index(Request $request, CsvWriter $csvWriter)
    {
        // some shared logic...

        $query = User::query()
            ->whereActive()
            ->whereStatus($request->query('status'));

        // format check(s) and format specific logic...

        if ($this->wantsCsv($request)) {

            // return a CSV...

            $query->each(function ($user) use ($csvWriter) {
                $csvWriter->addRow($user->only(['name', 'email']));
            });

            return response()->download($csvWriter->file(), "Users.csv", [
                'Content-type' => 'text/csv',
            ]);
       }

       // return a webpage...

        $memberships = Membership::all();

        return view('users.index', [
            'memberships' => $memberships,
            'users' => $this->query->paginate(),
        ]);
    }
}
```

You might notice a few things about the above controller:

1. There is some initial shared logic between all the formats, i.e. preparing the query.
2. If the user is requesting the webpage, the `CsvWriter` is never used.
3. As we add more formats, we are going to no doubt be injecting more dependencies that are not needed in the other response types.
4. More response types also mean more checks in the `if` chain.
5. The web page also has format specific logic, i.e. it requires the `$memberships` collection, which is used (perhaps) to populate a dropdown on the webpage, but is not needed in the CSV download.

This package cleans up this style of controller. Let me show you how...

### Cleaning up the controller

[](#cleaning-up-the-controller)

The first step to refactoring the controller is to replace the format specific logic with the response object. You will no doubt do this step last, but I think it is easier to demonstrate it this way.

```
class UserController
{
    public function index(Request $request, CsvWriter $csvWriter, )
    {
        $query = User::query()
            ->whereActive()
            ->whereStatus($request->query('status'));

        return UserIndexResponse::make(['query' => $query]);
    }
}
```

You can pass values into the response object by passing an array of data to the static `make` method. This is similar to how you may already be sending view data `view('users.index', ['some' => 'data'])`.

### The response object

[](#the-response-object)

In order to support a particular response format, you need to add a corresponding response method. If you want to provide your blog posts in mp3 audio format, you would add a `toMp3Response` method to you response object.

You can type hint these methods and the dependencies will be resolved from the container. In our example we are supporting HTML and CSV formats.

```
use TiMacDonald\MultiFormat\Response;

class UserResponse extends Response
{
    public function toCsvResponse(CsvWriter $writer)
    {
        $this->query->each(function ($user) use ($writer) {
            $writer->addRow($user->only(['name', 'email']));
        });

        return response()->download($writer->file(), "Users.csv", [
            'Content-type' => 'text/csv',
        ]);
    }

    public function toHtmlResponse()
    {
        $memberships = Membership::all();

        return view('users.index', [
            'memberships' => $memberships,
            'users' => $this->query->paginate(),
        ]);
    }
}
```

You can see the `toCsvResponse` method has type hinted the `CsvWriter`. This dependency is only resolved when the request format is CSV. You can also magically access any of the data you passed into the `make` method as an attribute on the object e.g. `$this->query`.

That is all there is to it really. Below are some more detailed docs and features.

Detecting response format
-------------------------

[](#detecting-response-format)

The response object will automatically detect the requested response format by checking for a file extension on the request's url and will fallback to the `Accept` header if no extension is found. Under the hood we are using Symfony's `MimeTypes` class to detect the extension. We then fallback to Laravel's `Request::format()` method. The first matching mime type and first matching extension will be used.

You do not *have* to support file extensions. This is entirely in your control. If you only want to support the `Accept` header than set up your routing to not supportextensions.

### Why file extensions?

[](#why-file-extensions)

It is pretty standard for an API to handle content negotiation with the `Accept` header. However it is often handy to be able to specify the response format with a file extension as well. This is probably most handy from a web interface where you can link the the same url but provide an extension to tell the server what format you want.

```
Downloads

    CSV
    PDF

```

This pattern is used in a lot of places. A good example of this is Reddit. Append `.json` to any url on reddit and you will get a JSON formatted response.

See for yourself:

-
-

Response format methods
-----------------------

[](#response-format-methods)

In order to support a format, you create a `to{Format}Response` method, where `{Format}` is the formats file extension. e.g.

- CSV: `toCsvResponse()`
- JSON: `toJsonResponse()`
- HTML: `toHtmlResponse()`
- XLSX: `toXlsxResponse()`

### Dependency Injection

[](#dependency-injection)

As mentioned previously, the format method will be called by the container, allowing you to resolve **format specific dependencies** from the container. As seen in the basic usage example, the html format has no dependencies, however the csv format has a `CsvWriter` dependency.

Default response format
-----------------------

[](#default-response-format)

It is possible to set a default response format, either from the calling controller, or from within the response object itself. This default format will be used if the url and the `Accept` header have no set value, or if no matches are found against existing `Accept` types.

### In the controller

[](#in-the-controller)

```
class UserController
{
    public function index()
    {
        //...

        return UserResponse::make(['query' => $query])
            ->withDefaultFormat('csv');
    }
}
```

### In the response object

[](#in-the-response-object)

```
class UserResponse extends Response
{
    protected $defaultFormat = 'csv';

    // ...
}
```

Overriding formats
------------------

[](#overriding-formats)

If there is a situation where the mime type you want to support is not being converted to the correct extension, either because it doesn't exist in the underlying libraries, or because it is matching the first extension and you want to use another, it is possible for you to manually specify overrides.

Look at `audio/mpeg` for example. There are several extensions associated with this content type.

```
'audio/mpeg' => ['mpga', 'mp2', 'mp2a', 'mp3', 'm2a', 'm3a'],
```

This package will resolve the first match, i.e. `mpga` as the format type. If you want to override this extension, you can do the following...

### In the controller

[](#in-the-controller-1)

```
class UserController
{
    public function index()
    {
        //...

        return UserResponse::make(['query' => $query])
            ->withFormatOverrides([
                'audio/mpeg' => 'mp3',
            ]);
    }
}
```

### In the response object

[](#in-the-response-object-1)

```
class UserResponse extends Response
{
    protected $formatOverrides = [
        'audio/mpeg' => 'mp3',
    ];

    // ...
}
```

The above would result in `toMp3Response` being called if the Accept header is `audio/mpeg`.

Routing
-------

[](#routing)

If you are wanting to embrace file extensions as a way of specifying response formats, you should explicilty specify the allowed formats in your routes file. This package does not provide any routing helpers (yet), but here is an example of how you can do it currently.

```
Route::get('users{extension?}', [
    'as' => 'users.index',
    'uses' => 'UserController@index',
    // this is what we need to add...
    'where' => [
        'extension' => '^\.(pdf|csv|xlsx)$',
    ],
]);
```

This route will be able to respond to the following urls and formats in the response object...

-  \[HTML\]
-  \[PDF\]
-  \[CSV\]
-  \[XLSX\]

I hate magic
------------

[](#i-hate-magic)

That's cool. Not everyone loves it. You don't have to use the `make` method. Just add your own contructor and set your class attributes as you like!

```
class UserResponse extends Response
{
    /**
     * @var \Illuminate\Database\Eloquent\Builder
     */
    private $query;

    public function __construct(Builder $query)
    {
        $this->query = $query;
    }
}

//...

return new UserResponse($query);
```

The Journey
-----------

[](#the-journey)

You've read the readme, you've seen the code, now read the journey. If you wanna see how I came to this solution, you can read my blog post: . Warning: it's a bit of a rant.

tl;dr; DHH and Adam Wathan are awesome.

Thanksware
----------

[](#thanksware)

You are free to use this package, but I ask that you reach out to someone (not me) who has previously, or is currently, maintaining or contributing to an open source library you are using in your project and thank them for their work. Consider your entire tech stack: packages, frameworks, languages, databases, operating systems, frontend, backend, etc.

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity25

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 90% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~498 days

Total

2

Last Release

1998d ago

Major Versions

v1.0.0 → 2.x-dev2020-11-23

### Community

Maintainers

![](https://www.gravatar.com/avatar/407c551b36817af2c26c7719fa6a16b8767ed7096d2930bf8e001237727ba847?d=identicon)[timacdonald](/maintainers/timacdonald)

---

Top Contributors

[![timacdonald](https://avatars.githubusercontent.com/u/24803032?v=4)](https://github.com/timacdonald "timacdonald (9 commits)")[![dependabot-preview[bot]](https://avatars.githubusercontent.com/in/2141?v=4)](https://github.com/dependabot-preview[bot] "dependabot-preview[bot] (1 commits)")

---

Tags

content-negotiationlaravelmutiformatresponselaravelmultiformatresponsableresponse objects

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/timacdonald-multiformat-response-objects/health.svg)

```
[![Health](https://phpackages.com/badges/timacdonald-multiformat-response-objects/health.svg)](https://phpackages.com/packages/timacdonald-multiformat-response-objects)
```

###  Alternatives

[essa/api-tool-kit

set of tools to build an api with laravel

52680.5k](/packages/essa-api-tool-kit)[resend/resend-laravel

Resend for Laravel

1191.4M6](/packages/resend-resend-laravel)[joggapp/laravel-aws-sns

Laravel package for the SNS events by AWS

3171.8k](/packages/joggapp-laravel-aws-sns)[simplestats-io/laravel-client

Client for SimpleStats!

4515.5k](/packages/simplestats-io-laravel-client)[dragon-code/laravel-json-response

Automatically always return a response in JSON format

1118.6k1](/packages/dragon-code-laravel-json-response)[surface/laravel-webfinger

A Laravel package to create an ActivityPub webfinger.

113.8k](/packages/surface-laravel-webfinger)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
