Laravel 10.4 version has been released today and there is a nice feature with it and that is File::json() method. Austin White contributed these features. Now using this method helper, we do not need to fetch json files first. We can easily read JSON files using File::json() method from Laravel 10.4 version.

laravel-10-read-json-file

Here we directly can access the data like below:

// Before
$contents = File::get('product.json');
$data = json_decode($contents, true);
 
// After
$data = File::json('product.json');

 

You can follow this way also

<?php

$contents = File::get(base_path('path/to/file.json'));
$json = json_decode(json: $contents, associative: true);

//or

$json = File::json(base_path('path/to/file.json'));

//even

$json = Storage::json('path/to/file.json');

 

You can handle errors like this:

<?php

$json = Storage::json('path/to/file.json', JSON_THROW_ON_ERROR);
$json = File::json('path/to/file.json', JSON_THROW_ON_ERROR);

 

Read also: Laravel 10 New Feature - Laravel Pennant Overview

 

Reading a JSON file in Laravel is a straightforward process using the Storage facade and PHP's built-in json_decode function. By following the steps outlined in this tutorial, you can easily read and parse JSON files in your Laravel applications, enabling you to work with JSON data seamlessly.

For more advanced scenarios, such as handling large JSON files or interacting with external APIs, Laravel offers additional features and packages that can further streamline your development workflow.