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

Lead Front End Developer
Remote
continued
Full-Stack Laravel Developer
Cologne
Revive Interior
Intermediate PHP Developer (Full Stack | CakePHP | Laravel | Vue | jQuery)
Remote
continued
Senior PHP Developer (Full Stack | CakePHP | Laravel | Vue | jQuery)
Remote
continued
Laravel Developer
Amsterdam (partially remote possible)
Let's Book
Web Developer (Laravel)
Tweed Heads, New South Wales, AUSTRALIA
Tursa Employment & Training
Laravel Experts needed-Remote position
Remote
Golden Sky ROI