Cover image for Quick Tip: Creating pretty JSON files with Laravel

Quick Tip: Creating pretty JSON files with Laravel

vittorioe profile image Vittorio Emmermann Originally published at vittorio.dev ・1 min read

Often I had a situation where my Apps had to generate a JSON file. For example, I'd write a CLI App for package development. This package had to write JSON pretty formatted to the generated composer JSON.

Here is a quick hint of how to generate this JSON string nice and smooth with laravel:

$json = Collection::make([
    'name' => 'Test',
    'description' => 'Another awesome laravel package',
    'license' => 'MIT'

This snipped will give you a $json Variable, which you can print to a file without any stress. It's pretty, escaped and with all formattings you need. We work here with Collection, a class from Laravel itself. Before using it you have to import it at the top of your file:

use Illuminate\Support\Collection;

For the example above, see here the output:

JSON Preview

That's it for now. With this variable you can print in files like a CloudFront Configuration, a composer.json for code generation or other things devs need for all-day work.


markdown guide