LaraCSV – Generate CSV files from your Eloquent models

LaraCSV – Generate CSV files from your Eloquent models

LaraCSV is a new package from Muhammad Usman that allows you to fluently generate CSV files from your Eloquent Models.

Here is a code sample to show how simple it is to get started:

$users = User::get(); // All users
$csvExporter = new \Laracsv\Export();
$csvExporter->build($users, ['email', 'name'])->download();

If you run this a CSV file will be downloaded with the user information:

email,name
eric@example.com,"Eric L. Barnes"
john@example.com,"John Smith"
bob@example.com,"Bob Jones"

Outside of these basic options it also includes some more powerful features:

Changing a field value

$csvExporter = new \Laracsv\Export();
$users = User::get();

// Register the hook before building
$csvExporter->beforeEach(function ($user) {
    $user->created_at = date('f', strtotime($user->created_at)); 
});

$csvExporter->build($users, ['email', 'name' => 'Full Name', 'created_at' => 'Joined']);

Adding a new column

// The notes field doesn't exist so values for this field will be blank by default 
$csvExporter->beforeEach(function ($user) {
    // Now notes field will have this value
    $user->notes = 'Add your notes'; 
});

$csvExporter->build($users, ['email', 'notes']);

Eloquent Relationships

This will get the product title and the related category’s title, a one to one relationship:

$products = Products::with('category')->get();
$csvExporter->build($products, ['title', 'category.title']);

See the project on Github and check out its readme for documentation and more examples.


Filed in: Laravel Packages / CSV


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Senior Laravel Engineer
Remote okay (must already live in USA)
Hawthorne Effect
Senior Software Engineer (Remote - Contract)
Remote
Koodi Systems
PHP Developer
Pittsburgh / Remote
Sequoia Waste Solutions
Software Developer
Eindhoven
Simac IDS
Application Developer Level II (CakePHP / MySql / Vue.js)
Lancaster, PA
Harbor Compliance
FULL STACK LARAVEL DEVELOPER
LONDON - WEST END
AMPERSAND HEATLH
Mid/Senior Laravel Developer - U.S. Only
Kenner, Louisiana
Profit Miner Technologies