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', 'CSVController@userCSV');
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. ?
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.