How to create a JSON text file for download in Laravel 5.3?
In this post we will give you information about How to create a JSON text file for download in Laravel 5.3?. Hear we will give you detail about How to create a JSON text file for download in Laravel 5.3?And how to use it also give you demo for it if it is necessary.
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
- Route::get('download-jsonfile',array('as'=>'file.download','uses'=>'FileController@downloadJSONFile'));
Route::get('download-jsonfile', array('as'=> 'file.download', 'uses' => 'FileController@downloadJSONFile'));
Controller: FileController.php
- <!--?php
- namespace AppHttpControllers;
- use File;
- class FileController extends Controller
- {
- public functiondownloadJSONFile(){
- $data=json_encode(['Text 1','Text 2','Text 3','Text 4','Text 5']);
- $file=time().'_file.json';
- $destinationPath=public_path()."/upload/json/";
- if(!is_dir($destinationPath)){mkdir($destinationPath,0777,true);}
- File::put($destinationPath.$file,$data);
- returnresponse()->download($destinationPath.$file);
- }
- }
download($destinationPath.$file); } }
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.
use File must be define in top of your controller.
Hope this code and post will helped you for implement How to create a JSON text file for download in Laravel 5.3?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs