How to Read JSON File in Laravel?
In this post, I will show you how to get data from json file in laravel application.
We'll retrieve data from the storage and public folders using the Storage facade and file_get_contents function. Let's look at the examples below.
1. Read JSON File using file_get_contents()
First, you need to create json file on your public folder like this way:
public/data/info.json
{
"name": "John Doe",
"email": "john@example.com",
"age": 30
}
let's see the controller code and output:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class StorageController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
// Read the contents of the JSON file
$json = file_get_contents(public_path('data/info.json'));
// Decode JSON into an associative array
$data = json_decode($json, true);
return response()->json($data);
}
}
You will see the ouput like this way:
{"name":"John Doe","email":"john@example.com","age":30}
2. Read JSON File using Storage Facade
First, you need to create json file on your storage folder folder like this way:
storage/app/public/data.json
{
"name": "John Doe",
"email": "john@example.com",
"age": 30
}
let's see the controller code and output:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class StorageController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
// Read the contents of the JSON file
$json = Storage::disk("public")->get('data.json');
// Decode JSON into an associative array
$data = json_decode($json, true);
return response()->json($data);
}
}
You will see the ouput like this way:
{"name":"John Doe","email":"john@example.com","age":30}
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel 11 Display Image from Storage Folder Example
- Customize Laravel Jetstream Registration and Login Example
- Laravel 11 Store JSON Format Data in Database Tutorial
- Laravel 11 JSON Web Token(JWT) API Authentication Tutorial
- How to Save JSON Data in Database in Laravel 11?
- How to Convert JSON to Collection in Laravel?
- How to Add Active Class Dynamically in Laravel?
- Laravel Blade Foreach First Element Example
- Laravel Dompdf Set Custom Paper Size Example
- Laravel Get File Mime Type from Storage Example
- Laravel Get File Contents from Storage Example
- How to Install JQuery in Laravel Vite?