LaraCSV – Generate CSV files from your Eloquent models

Packages

April 24th, 2017

laravel-csv-lead.png

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:

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

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

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

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

Changing a field value

1$csvExporter = new \Laracsv\Export();
2$users = User::get();
3
4// Register the hook before building
5$csvExporter->beforeEach(function ($user) {
6 $user->created_at = date('f', strtotime($user->created_at));
7});
8
9$csvExporter->build($users, ['email', 'name' => 'Full Name', 'created_at' => 'Joined']);

Adding a new column

1// The notes field doesn't exist so values for this field will be blank by default
2$csvExporter->beforeEach(function ($user) {
3 // Now notes field will have this value
4 $user->notes = 'Add your notes';
5});
6
7$csvExporter->build($users, ['email', 'notes']);

Eloquent Relationships

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

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

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

Filed in:

Eric L. Barnes

Eric is the creator of Laravel News and has been covering Laravel since 2012.

Laravel News Partners