Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Formatter Laravel Package

soapbox/laravel-formatter

Laravel Formatter converts arrays, collections, and Eloquent models into JSON, XML, CSV, YAML, and other formats. It provides a simple, extensible API, customizable formatters, and clean output handling for exporting data in Laravel applications.

View on GitHub
Deep Wiki
Context7

Getting Started

Install the package with Composer:

composer require soapbox/laravel-formatter

On Laravel 5.5+ the service provider and Formatter facade are auto-discovered. On older Laravel versions, register them manually in config/app.php:

'providers' => [
    Soapbox\Formatter\FormatterServiceProvider::class,
],

'aliases' => [
    'Formatter' => Soapbox\Formatter\Facades\Formatter::class,
],

The first thing to read is the README and then src/Formatter.php, which exposes the entry points: Formatter::make($data, $type) and the shorthand helpers such as Formatter::json($data), Formatter::xml($data), Formatter::yaml($data), Formatter::csv($data), and Formatter::array($data). Format constants (Formatter::JSON, Formatter::XML, Formatter::YAML, Formatter::CSV, Formatter::ARR) are also defined there.

The most common first use case is converting an associative array into an API-friendly payload:

use Soapbox\Formatter\Formatter;

$payload = [
    'name' => 'Jane Doe',
    'email' => '[email protected]',
];

$json = Formatter::make($payload, Formatter::ARR)->toJson();
$xml  = Formatter::make($payload, Formatter::ARR)->toXml();

Or the reverse — accepting a client-supplied JSON/XML string and normalizing it to an array:

$array = Formatter::make($request->getContent(), Formatter::JSON)->toArray();

Start with the array → JSON/XML direction; it is the least surprising path and the one most projects actually need.

Implementation Patterns

Explicit source and target formats. The formatter is a two-step pipeline: build with the input format, then call the to*() method for the output format. Keep both explicit in your code so the conversion path is obvious:

$formatter = Formatter::make($data, Formatter::ARR);

return response($formatter->toXml(), 200)
    ->header('Content-Type', 'application/xml');

Normalize inbound request bodies. A practical integration is a middleware or form request that detects Content-Type and converts JSON, XML, or CSV into an array before validation:

$type = match ($request->header('Content-Type')) {
    'application/xml', 'text/xml' => Formatter::XML,
    'text/csv'                    => Formatter::CSV,
    default                       => Formatter::JSON,
};

$request->merge(Formatter::make($request->getContent(), $type)->toArray());

Export endpoints. For a CSV download, build an array of rows and stream the result:

$rows = User::query()->get(['name', 'email'])->toArray();

return response(Formatter::make($rows, Formatter::ARR)->toCsv())
    ->header('Content-Type', 'text/csv')
    ->header('Content-Disposition', 'attachment; filename="users.csv"');

Wrap it in your own service. Because the package API is small and static-ish, it is worth hiding it behind an application service (App\Support\DataFormatter) so that swapping the implementation later does not ripple through controllers. This also gives you a single place to handle exceptions and default options.

Use it at the boundary, not in the domain. Convert at the edges of the application — controllers, console commands, jobs that ingest files — and keep domain code working with arrays/collections. This keeps the formatter's quirks out of business logic.

Custom formatters. The formatter is designed to be extended. If you need a format it does not ship (e.g. a proprietary tab-delimited format), check Formatter::extend() in src/Formatter.php and the src/Formatters/ directory for the contract a formatter implements. Register custom formats during a service provider's boot() method.

Pair with validation, not instead of it. Use the formatter to get data into an array, then validate with a FormRequest or Validator::make(). Do not trust XML/CSV input as structurally safe just because it parsed.

Gotchas and Tips

Age and framework compatibility are the biggest risk. The last release was in 2018 and the package was written for the Laravel 4/5 era. Its Composer constraints on illuminate/support may block installation on Laravel 9/10/11. Check composer.json before committing to it; if it conflicts, you are choosing between --ignore-platform-reqs (fragile), a fork with widened constraints, or a native alternative. For JSON, json_encode/json_decode is already in PHP; for CSV, league/csv; for XML, SimpleXMLElement or spatie/array-to-xml; for YAML, symfony/yaml.

XML output is where most surprises live. Numeric-indexed arrays, nested arrays, and empty values do not always produce the XML shape you expect. Root element naming and attribute handling vary by version, so test the exact shape your consumers require rather than assuming. If the consumer is strict (SOAP, a legacy integration), inspect the generated string in a test.

YAML and CSV have their own dependencies and options. YAML support typically relies on symfony/yaml, so make sure it is installed. CSV methods take delimiter/enclosure-style arguments; defaults are comma and double-quote, which breaks on data containing embedded newlines or the delimiter itself. Verify round-tripping with messy real-world data, not clean fixtures.

Empty and scalar inputs behave inconsistently. Converting null, an empty array, or a scalar to XML/CSV/YAML can produce different results than converting a populated array. Add explicit tests for these cases, or guard in your wrapper service.

Exceptions are the debugging entry point. The package throws its own exception types under Soapbox\Formatter\Exceptions. Catch and log those specifically rather than swallowing \Exception, and include the source format and a truncated input in your log context — malformed input is the most common failure.

Config and facade caching. If you register custom formatters or configuration, remember php artisan config:clear after changes, and be aware that facade aliases are resolved at boot. In long-running workers (Octane, queue workers), any static state in a custom formatter will persist between requests — keep formatters stateless.

Do not use it as a serializer. This package converts data structures between formats; it does not understand Eloquent models, relations, hidden attributes, or API resources. Convert models with ->toArray() or an API Resource first, then format the resulting array. Trying to feed it a model directly will leak attributes you did not intend to expose.

Prefer a fork or wrapper if you keep it. If the package is already in your codebase and working, isolate it behind your own service and pin the version in composer.json. That gives you a clean migration path to native PHP functions or a maintained package when the next Laravel upgrade forces the issue.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jinas/dhivatar
store-doc/laravel-storage-driver
plus-it/laravel-translation-manager
diephp/perhaps
diephp/telegraph
osmaviation/spreadsheet
microsoft/fluentui-system-icons
mmccook/php-json-canonicalization-scheme
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console
pnscripts/filament-broadquill-lite
pnscripts/laravel-sentfold-lite
vleap/mx-sdk-laravel-internal
twidpay/utils
htetmyathlaing/scout-elasticsearch-driver
artisan-toolbox/front-awesome
ls/client-assistant
users-au/laravel-client
cgv/localized-resource