Laravel - export database table to csv file using LaraCSV

April 23, 2017 | Category : Laravel 5 Laravel

We generally need to generate csv file for export from database table because it is very easy to read data or use something else. In this article we will learn how to create csv file of table data and download that csv file.

In this example we will export users table data in csv file. There are several packages for generate csv file, but we will use LaraCSV package use for create csv file. LaraCSV provide very easy and quick way to generate csv file. So you can simply implement by following tuto.

First we require "users" table, if you haven't created "users" table then you can create by create migration, after create "users" migration and user model, you must have some dummy data on users table. After that we require to install LaraCSV package by following command:

composer require "usmanhalalit/laracsv:1.*@dev"

After, installation completed, we make very simple example of create csv file to users table data. So you have to simple create bellow route on your laravel application.





| Web Routes



| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!



Route::get('download-csv', function () {

$users = \App\User::all();

$csvExporter = new \Laracsv\Export();

return $csvExporter->build($users, ['id', 'name', 'email'])->download();


Now, run your application and open "download-csv" route, you can download.

If you want to more learn from laracsv then click here : LaraCSV.