How to read json file in Laravel?

In this post, I will show with you how to read json file in Laravel. To read a JSON file in Laravel, you can use PHP’s built-in functions like file_get_contents() combined with json_decode()

We’ll retrieve data from the storage and public folders using Storage facade.

Steps to Read JSON file in Laravel
  • Save the file in a directory within your Laravel such as the storage or public directory. For example, you can place it at: storage/app/public/test.json.
  • Laravel provides methods to handle files, such as Storage::disk(‘public’)->get()
  • Use json_decode() to convert the JSON content into a PHP array or object.
1. Read JSON file in Laravel using file_get_contents()

First, you need to create json file on your public folder like this method.

public/data/test.json
{
    "role": "admin",
    "varified": "yes",
    "type": "A"
}

Let’see the controller code and output:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class StorageController extends Controller
{
    public function index(Request $request)
    {
        $json = file_get_contents(public_path('data/test.json'));

        $data = json_decode($json, true);
       
        return response()->json($data);
    }
}
Output:
{"role":"admin","varified":"yes","type":"A"}
2. Read JSON file in Laravel using Storage Facade

First, you need to create json file on your storage folder like this method.

storage/app/public/test.json
{
    "role": "admin",
    "varified": "yes",
    "type": "A"
}

Let’see the controller code and output:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class StorageController extends Controller
{
    public function index(Request $request)
    {
        $json = Storage::disk("public")->get('test.json');

        $data = json_decode($json, true);
       
        return response()->json($data);
    }
}
Output:
{"role":"admin","varified":"yes","type":"A"}

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *