Simple Steps: Turn Database Data into JSON in Laravel - PHP

 Convert Database entries to JSON file in Laravel

Simple-Steps-Turn-Database-Data-into-JSON-in-Laravel-PHP

JSON is the most efficient way of data transfer if you are working with API's . While working with api's in Laravel we provide the output as JSON. Json works extremely well with databases like MySQL, NoSQL and MongoDB etc. In this article we will learn how to convert database data to JSON file easily.


Here are the steps to follow.

  • Create your route
  • Get your data from database
  • Decode the data with json_decode()
  • Write the decoded data to a json file

Step 1 : Create your route

Route::get('user/downloadjson', [HomeController::class,'downloadUserJson'])->name('download-user-json');


Step 2 : Code on your controller

public function downloadUserJson(){
        try{
            $data = DB::table('users')->get()->toArray();
            $json_data = json_encode($data);
            $fp = fopen('results.json', 'w');
            fwrite($fp, $json_data);
            fclose($fp);
            $file_url = asset("results.json");  
            return response()->json(["response"=>['code'=>200,'message'=>"Downloaded successfully.",'file_url'=>$file_url]]);
        }catch(\Exception $e){
            return false;
        }
    }


Output :

{
    "response": {
        "code": 200,
        "message": "Downloaded successfully.",
        "file_url": "http://127.0.0.1:8000/results.json"
    }
}


How to convert data to JSON file from Database in Laravel - PHP


Previous Post Next Post

Contact Form