Create Json File and Write It With Dynamic Data in Laravel

Hello artisan, you may face a situation like you want to fetch some data from server and need to create a json file and then read that json file with this data. In this case, how you can solve this problem or how we can do it in laravel application? If you do not know how to create .json file and write into that file with data using Laravel then this example is for you.

Let's see the example code of how we can create a dynamic json file and then write it with our dynamic data in laravel application.

routes/web.php

use App\Models\Product;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;

Route::get('test',function(){
    $products = Product::query()
                    ->get();

    Storage::disk('public')->put('product.json', json_encode($products));

    dd('done');
});

 

Now you can load this file like:

use App\Models\Product;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;

Route::get('test',function(){
    $products = Product::query()
                    ->get();

    return Storage::disk('public')->get('product.json');
});

 

Read also: How to Define Singleton Route in Laravel 9?

 

Hope it can help you.

 

author-image
Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js