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

Share Me
  •  
  •  
  •  
  • 2
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    2
    Shares
How to create a text file for JSON and file download in Laravel?
How to create a text file for JSON and file download in Laravel?

Hello Dev’s Today I will show you how to How to create a text file for JSON and file download in Laravel . If we want create our own  new text file, html file, css file, php file, or any json file etc in Laravel application. Then we do not need to use any PHP library or any Class because Laravel Framwork Provide us its own “File” Facade. As File Class through we can create our own html file, txt file, php file etc as we want. In File Facade Class also provide  us several function like we can create file, remove file, or update file etc. Now here i am giving you a example of how to create json file in Laravel application.

We also want to download file that we created now, i mean we want to give download file, then we can also give download that file by using Laravel “Response” Class. So in Laravel Response Class can use for give response or redirect something, from one page to another page. So, basically how to give a create file and download that file example below.

Route :

Route::get('downloadJSONFile', array('as'=> 'downloadJSONFile', 'uses' => 'JSONFileController@downloadJSONFile'));

JSONFileController Controller :

namespace App\Http\Controllers;

use View;
use File;
use Response;

class JSONFileController extends Controller
{
 public function downloadJSONFile(){
   $data = json_encode(['Example 1','Example 2','Example 3',]);
   $fileName = time() . '_datafile.json';
   File::put(public_path('/upload/json/'.$fileName),$data);
   return Response::download(public_path('/upload/jsonfile/'.$fileName));
 }
}

Read Also : Laravel 8 Login with Google Account Example

Thanks for read. I hope it help you. For more you can follow us on facebook.

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →