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...