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.
routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| 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.
Do you like below Tutorials ?
- PHP Laravel 5.5 - import export data into excel and csv using maatwebsite
- Laravel 7.x and 6.x create custom facade example from scratch
- Node JS - Get Real time online users counter using socket io example
- PHP Laravel 7.x and 6.x - Bootstrap Admin Theme Integration example from scratch
- MySQL Query - How to select records of today to next Sunday ?
- Laravel 7.x and 6.x - username custom validation example
- Laravel 5.5 - Import Extract zip file using chumper/zipper package
- PHP Laravel Set Custom Validation Error Messages Example