How to create a JSON text file for download in Laravel 5.3?

How to create a JSON text file for download in Laravel 5.3?

In this post, i will tell you how to create a json text file for download in Laravel 5.3

With Laravel, you do not need to use any PHP library because Laravel provide so many helper method and facade and File facade is one of them. Laravel has a powerful filesystem abstraction Flysystem PHP package.

You will find the configuration file for filesystem in config/filesystems.php.

I here focus on File facade because i am going to use this facade in below example.

File::put method is used to store raw file content in a specific location or disk.

There are number of function with File Facade Class such as create file, update file and remove file.

Route: web.php
  1. Route::get('download-jsonfile', array('as'=> '', 'uses' => 'FileController@downloadJSONFile'));
Controller: FileController.php
  1. namespace App\Http\Controllers;
  2. use File;
  3. class FileController extends Controller
  4. {
  5.     public function downloadJSONFile(){
  6.      $data = json_encode(['Text 1','Text 2','Text 3','Text 4','Text 5']);
  7.      $file = time() . '_file.json';
  8.      $destinationPath=public_path()."/upload/json/";
  9. if (!is_dir($destinationPath)) { mkdir($destinationPath,0777,true); }
  10.      File::put($destinationPath.$file,$data);
  11.      return response()->download($destinationPath.$file);
  12.     }
  13. }

Here i use download method to generate a response that force the client browser to download the file.

The response helper is used to generate a response to be sent back to the user's browser. You will notice that i check if directory is exist in specified location or not using is_dir command if not exist then i create a directory using mkdir command with full permission and then put file in specified location.

Phone: (+91) 8800417876
Noida, 201301