Md Obydullah Follow I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and web development.

Laravel Export Database in CSV Format Using LaraCSV

Published on May 31, 2019 59 sec read

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

  1. Install LaraCSV Package
  2. Create a Controller
  3. Define a Route
  4. Test the Exporter

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:

CSVController.php
<?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:

web.php
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. 🙂

You're welcome to suggest any article to write!

Md Obydullah Follow I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and web development.

2 Replies to “Laravel Export Database in CSV Format Using LaraCSV”

Leave a Reply

Your email address will not be published. Required fields are marked *