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'));
- namespace App\Http\Controllers;
- use File;
- class FileController extends Controller
- {
- public function downloadJSONFile(){
- $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);
- return response()->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.