Laravel Export Database in CSV Format Using LaraCSV
Hello, today I am going to share how to export database in CSV format using LaraCSV package in Laravel. We are going to do this in four steps only. Let’s follow the steps.
Table of Contents
Step 1 : Install LaraCSV Package
Go to your laravel project and run this composer command to install LaraCSV:
composer require usmanhalalit/laracsv
Step 2 : Create a Controller
We have installed LaraCSV. We need to create a controller. Let’s created a controller named “CSVController“. Run this command to create the controller:
php artisan make:controller CSVController
Now go to App>Http>Controllers and open CSVController.php and paste this code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class CSVController extends Controller
{
public function userCSV()
{
$users = User::get(); // All users
$csvExporter = new \Laracsv\Export();
$csvExporter->build($users, ['name', 'email', 'created_at'])->download();
}
}
In the controller, we have defined a function called userCSV() to export users table in CSV format.
Step 3 : Define a Route
Let’s create a route to connect to userCSV() function. Open web.php from routes folder and paste this line:
Route::get('user-csv', '[email protected]');
Step 4 : Test the Exporter
We have finished all the tasks. It’s time to test the exporter. Let’s test. Run the project and visit the route http://localhost:8000/user-csv
. It will make your users table in CSV format and will download automatically.
After visiting the route, a file will automatically download. I visited and downloaded a file named ‘2019-05-31_080922.csv‘. I opened the file and saw the output like:

You can find more details from GitHub Repository. Thank you. ?
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)