Creating pretty JSON files with Laravel

Vittorio Emmermann 4 months ago Follow on Twitter

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:

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.

Do you want to stay up to date?

I'll never spam you, I swear. My newsletter will be send all 2 or 3 weeks with some interesting things for you.

Also you can follow me on twitter where I post recent learnings, hints and comments.

Imprint Data privacy Contact