Laravel 5 create a json or text file using file system

By | June 23, 2018
Laravel 5 create a json file using file system

Hello friends, in this article i am going to tell you about laravel 5 create a json or text file using file system. In the application sometimes we need to create or generate a new file with some data through the srcipt. So for that their are some functions  already available in php like fwrite or file_put_content.

But here you will learn about a technique provided by laravel. Laravel provides simple powerful helper methods for file handling. So we don’t need to use inbuilt php method in laravel application. Laravel has various Facade to helper methods. Here i will use File facade to create a json or text file with some sample data.

We will use File::put() method to write the content into a new file.

Laravel provides various helper methods with File Facade for create, update, delete, read file from our system.

So let’s start with a simple example. In this example i will create a json file

First we will create route to handle the request.

Add Route :

Open routes/web.php file and put the following route into this file.

 routes/web.php

Route::get('download-jsonfile', array('as'=> 'file.download', 'uses' => 'FileController@downloadJSONFile'));

After creating a route we will create a controller FileController in Controller directory and a method named as downloadJSONFile() method into ithis controller. So let’s create FileController file and put the below code into this controller file.

app/Http/Controller/FileController.php

namespace App\Http\Controllers;
use File;
class FileController extends Controller
{
    public function downloadJSONFile(){
      $data = json_encode(['Element 1','Element 2','Element 3','Element 4','Element 5']);
      $file = time() .rand(). '_file.json';
      $destinationPath=public_path()."/upload/";
      if (!is_dir($destinationPath)) {  mkdir($destinationPath,0777,true);  }
      File::put($destinationPath.$file,$data);
      return response()->download($destinationPath.$file);
    }
}

In the above script i am using use File  to include File Facade into this controller. And using some raw array data to fill into the file and giving a random and unique name to the file by using time() and rand() function. Creating this file into the upload directory under public directory.

After putting the json encoded content into the file i am using response()->download() method to download this newly created file.

After completing the above steps when you will open your application with download-jsonfile url. You will get a new file into upload directory and it will also be download into your system.