برای نصب پکیج LaraCSV دستور زیر را اجرا می کنیم:
composer require "usmanhalalit/laracsv:1.*@dev"
برای ساخت فایل CSV از دستور:
$csvExporter->build(User::get(), ['email', 'name', 'created_at']);
برای دانلود فایل CSV از دستور زیر استفاده می کنیم:
$csvExporter->download();
برای نام دادن به فایل CSVاز دستور زیر استفاده می کنیم:
$csvExporter->download('active_users.csv');
برای تبدیل خروجی CSV به فایلهای مختلف از دستورات زیر استفاده می کنیم:
$csv = $csvExporter->getCsv();
$csv->toHTML(); // To output the CSV as an HTML table
$csv->jsonSerialize()(); // To turn the CSV in to an array
$csv = (string) $csv; // To get the CSV as string
echo $csv; // To print the CSV
برای تعریف header فایل CSV از دستور زیر استفاده می کنیم:
$csvExporter->build(User::get(), ['email', 'name' => 'Full Name', 'created_at' => 'Joined']);
برای تغییرات در خروجی فایل CSV از فرمان های زیر استفاده می کنیم:
$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']);
برای اضافه کردن فیلدی به فایل CSV از دستورات زیر استفاده می کنیم:
// 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']);
برای استفاده از relation بین جداول در دیتابیس از دستورات زیر استفاده می کنیم:
$csvExporter->build($products, ['title', 'category.title']);
$products = Product::where('order_count', '>', 10)->orderBy('order_count', 'desc')->get();
$fields = ['id', 'title','original_price' => 'Market Price', 'category_ids',];
$csvExporter = new \Laracsv\Export();
$csvExporter->beforeEach(function ($product) {
$product->category_ids = implode(', ', $product->categories->pluck('id')->toArray());
});