In this tutorial you will learn about the Laravel 8 Create JSON Text File for Download using File and Response and its application with practical example.
In this Laravel 8 Create JSON Text File for Download using File and Response tutorial I will show you how to create json text file using file facade and download using response class in laravel. In this tutorial you will learn to create a json text file using file facade and then download it using laravel response class. In this article I will share example to create and download json text file in laravel application. In this tutorial you will learn convert form data or text file data into json format text file and download it using response class. We will be using laravel File facade class to create your own html file, txt file, php file etc as you want. File Facade Classis meant for laravel file handling with file facade you can create file, remove file, update file etc. We will also be using Laravel “Response” Class. In this example we will be using Laravel Response Class download that file.
Laravel 8 Create JSON Text File for Download using File and Response
In this step by step tutorial I will demonstrate you with example on how to create json text file using file facade and download using response class in laravel. Please follow the instruction given below:
Create Route
In this step we will define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 |
Route::get('json-file-download', array('as'=> 'jsonFileDownload', 'uses' => 'JsonController@jsonFileDownload')); |
Now, lets create a controller file named JsonController.php in app/Http/Controllers/ directory. Open the JsonController.php file and put the following code in it.
app/Http/Controllers/JsonController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php namespace App\Http\Controllers; use Response; use View; use File; class JsonController extends Controller { public function jsonFileDownload() { $data = json_encode(['Text One', 'Text Two', 'Text Three']); $jsongFile = time() . '_file.json'; File::put(public_path('/upload/json/'.$jsongFile), $data); return Response::download(public_path('/upload/jsonfile/'.$jsongFile)); } } |