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

Full-Stack Developer
Tampa, FL / Remote
Nu Image Medical
PHP Developer
Remote
X-Team
Full-Stack Developer
Sioux Falls, SD or Remote
Electric Pulp
Senior PHP / Vue.js Developer
Portland, OR / Remote
Bright Oak
Full Stack Vue.js Developer (Front-end focus)
Remote
LenderHomePage.com
Senior Laravel Web Application Developer
NYC or Remote
Happy Cog
Laravel Developer (Vue, SQL Server)
Geneva, Switzerland / Remote
World Trade Organization