Tuesday, July 5, 2016

How to Export CSV from Model in Laravel | How to Download Table Data / Database to CSV in Laravel

export csv from database


CSV is the best format to save data in a table structured format from your laravel application. It's almost look like excel but with a .csv extension. There is a certain steps by which you can download .csv format data from database.So Do follow the following process to export CSV from Model:


1. Make a route in routes.php file:
Route::get('/csv',[
 'uses'=>'UserController@download', 
 'as'=>'download'
 ]);
2. Let's create a method called 'download' in UserController.php :
public function download()
   {
      $table = User::all(); 
      $filename = "userList.csv";
      $handle = fopen($filename, 'w+');
      fputcsv($handle, array('Name', 'Email'));

        foreach($table as $row) {
         fputcsv($handle, array($row['name'], $row['email']));
        }

      fclose($handle);
      $headers = array('Content-Type' => 'text/csv');
      return Response::download($filename, 'userList.csv', $headers);
        }     


Now if you access the 'csv' route in your application you'll see a list of users name and email will be downloaded in a csv file from your application.

And That's how you can export CSV from Model in your laravel application. 

















Related Articles

0 comments:

Post a Comment