LaraCSV--从 Eloquent 模型中生成 CSV 文件

LaraCSV 是 Muhammad Usman 新发布的包,它允许你流畅的从 Eloquent 模型中生成csv文件。
这些代码样例是展示使用 LaraCSV 多简单。

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

如果你执行这个方法,将会下载一个包含用户信息的csv文件,例如:

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

除此的基础操作之外,他也包含一些更强大的特性:
调整字段值

   $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']);

添加一列

   // 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 关联关系
这个将会获取到商品名称和关联的种类名称,一个一对一关联关系

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

Github 上查看项目, 查看他的 readme 文档和更多例子。
可以试试这个。

翻译自:https://laravel-news.com/generate-csv-file...

本作品采用《CC 协议》,转载必须注明作者和本文链接
Keep Young, Keep Simple.
本帖由 Summer 于 6年前 加精
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 6
DukeAnn

做导入导出很方便了

6年前 评论

@ADKi 哈哈,这个主要是提供了简单的导出功能

6年前 评论

@JokerLinly 谢谢支持啊

6年前 评论

created_atye也是Carbon类

$user->created_at = date('f', strtotime($user->created_at));可以$user->created_at=$user->created_at->format('f');

6年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!