LaraCSV پکیج جدیدی برای فریم ورک Laravel است که به شما امکان می دهد به صورت ساده و سریع از Eloquent Model های خود خروجی csv تهیه کنید.
کد زیر به صورت ساده این کار را برای تان انجام می دهد:
$users = User::get(); // All users $csvExporter = new \Laracsv\Export(); $csvExporter->build($users, ['email', 'name'])->download();
اگر این کد را اجرا کنید یک فایل حاوی اطلاعات کاربران را دانلود خواهید کرد(به شرطی که جدول users را داشته باشید)
email,name [email protected],"Eric L. Barnes" [email protected],"John Smith" [email protected],"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 Relationships
در این مثال می خواهیم عنوان محصول و عنوان دسته بندی مربوطه آن را که از یک ارتباط یک به یک بگیریم
$products = Products::with('category')->get(); $csvExporter->build($products, ['title', 'category.title']);
پروژه را در Github ببینید و در مستندات و توضیحات آن نمونه کدهای بیشتر را بررسی کنید.
با سپاس